输入 words.txt 文件 python 3
inputting a words.txt file python 3
我不知道为什么 words.txt 没有显示完整的网格,下面是我必须执行的任务:
编写代码提示用户输入文件名,并尝试打开提供名称的文件。如果无法打开文件,则应要求用户提供另一个文件名;这应该一直持续到文件被成功打开。
该文件将在每一行中包含来自单词网格的一行。编写代码依次读取文件的每一行,删除换行符并将结果字符串附加到列表中 strings.After 输入完成网格应显示在屏幕上。
以下是我到目前为止执行的代码,如有任何帮助,我们将不胜感激:
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")
你需要 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
这将一直询问,直到提供有效文件。
注意:始终避免使用 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
下面的实现应该有效:
# 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")
我不知道为什么 words.txt 没有显示完整的网格,下面是我必须执行的任务:
编写代码提示用户输入文件名,并尝试打开提供名称的文件。如果无法打开文件,则应要求用户提供另一个文件名;这应该一直持续到文件被成功打开。
该文件将在每一行中包含来自单词网格的一行。编写代码依次读取文件的每一行,删除换行符并将结果字符串附加到列表中 strings.After 输入完成网格应显示在屏幕上。
以下是我到目前为止执行的代码,如有任何帮助,我们将不胜感激:
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")
你需要 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
这将一直询问,直到提供有效文件。
注意:始终避免使用 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
下面的实现应该有效:
# 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")