我很困惑为什么words.txt没有显示完整的网格,下面是我必须执行的任务:
编写代码以提示用户输入文件名,并尝试打开其名称已提供的文件。如果无法打开文件,则应要求用户提供另一个文件名;这应该继续,直到文件成功打开。
该文件将在每一行中包含单词grid中的一行。编写代码以反过来读取文件的每一行,删除换行符并将结果字符串附加到字符串列表中。输入完成后,网格应显示在屏幕上。
以下是我目前执行的代码,任何帮助将不胜感激:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
except IOError as e:
print ("File Does Not Exist")
答案 0 :(得分:1)
注意:始终避免使用file
,list
等变量名,因为它们是用python类型构建的
while True:
filename = raw_input(' filename: ')
try:
lines = [line.strip() for line in open(filename)]
print lines
break
except IOError as e:
print 'No file found'
continue
答案 1 :(得分:1)
以下实施应该有效:
# loop
while(True):
# don't use name 'file', it's a data type
the_file = raw_input("Enter a filename: ")
try:
with open(the_file) as a:
x = [line.strip() for line in a]
# I think you meant to print x, not a
print(x)
break
except IOError as e:
print("File Does Not Exist")
答案 2 :(得分:0)
你需要一个while循环吗?
while True:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
break
except IOError:
pass
这将一直询问,直到提供有效的文件。