这里是一年级的理工科学生。
我有一个任务,要求我们使用Python制作一个简单的游戏,它需要一个输入文件来创建游戏世界(2D网格)。然后,你应该通过用户输入给出移动命令。我的程序一次读取一行输入文件,使用以下命令创建世界:
def getFile():
try:
line = input()
except EOFError:
line = EOF
return line问题是,我后来需要接受输入来移动字符,但我不能这样做,因为它仍然希望读取文件输入,而文件中的最后一行是EOF字符,这会导致错误。特别是"EOF when reading a line“错误。
我怎么才能避免这个问题呢?
发布于 2014-11-12 02:59:34
听起来像是直接从stdin读取文件--类似于:
python3 my_game.py < game_world.txt相反,您需要将文件名作为参数传递给您的程序,这样stdin仍将连接到控制台:
python3 my_game.py game_world.txt然后get_file看起来更像是:
def getFile(file_name):
with open(file_name) as fh:
for line in fh:
return line发布于 2014-11-11 13:47:09
python3的文件交互方式是这样的:
# the open keyword opens a file in read-only mode by default
f = open("path/to/file.txt")
# read all the lines in the file and return them in a list
lines = f.readlines()
#or iterate them at the same time
for line in f:
#now get each character from each line
for char_in_line in line:
#do something
#close file
f.close()默认情况下,文件的行终止符是\n如果您想要其他东西,可以将其作为参数传递给open方法( newline参数。默认值=无=‘\n’):
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)https://stackoverflow.com/questions/26857900
复制相似问题