这是我到目前为止,我尝试的一切都说明文件没有打开?有什么基本方法可以解决这个问题吗?
liNames = []
while 1 == 1:
liNames += [raw_input("Tell me a name. Type DONE(all caps) if done entering:")]
if "DONE" in liNames:
break
del liNames[-1]
print liNames
name_file = open("names.txt","w")
line = name_file.writelines(liNames)
for line in name_file:
print line
name_file.close()
答案 0 :(得分:1)
在这一行之后具体说明评论的建议:
line = name_file.writelines(liNames)
插入以下新行:
name_file.close()
name_file = open("names.txt", "r") # or plain open("names.txt")
有了更多经验,你会把它写成:
with open("names.txt","w") as name_file:
name_file.writelines(liNames)
with open("names.txt") as name_file:
for line in name_file:
print line
凭借更多的经验;-),您将学习如何打开文件以阅读和。但这更棘手,而且尤其对于Windows上的文本文件来说很棘手。
答案 1 :(得分:0)
解决您的错误:
您只能在写入模式下打开它,读取它,在读取模式下打开它:
name_file = open("names.txt", "r")
或者只是:
name_file = open("names.txt")
由于python默认在读取模式下打开文件。
所以步骤是:
之后,阅读文件:
简而言之,就像这样:
name_file = open("names.txt","w")
line = name_file.writelines(liNames)
name_file.close()
name_file = open("names.txt")
for line in name_file:
print line
name_file.close()
要使事物看起来更整洁,请使用with
语句(它会自动关闭文件)
像这样:
with open('names.txt', 'w') as file_name:
line = name_file.writelines(liNames)
with open('names.txt', 'r') as file_name:
for line in name_file:
print line
答案 2 :(得分:0)
正如Tim Peters所说,当你在代码中打开文件时,你打开它进行写作。完成写入后,文件将在此模式下保持打开状态,直到您调用" close()"在最后一行。
如上所述,你应该这样做(一种可能的方式):
name_file = open("names.txt","w")
line = name_file.writelines(liNames)
name_file.close()
name_file = open("names.txt")
for line in name_file:
print line
name_file.close()
另一种方法是使用with
语句:
with open("nmes.txt", "w") as name_file:
name_file.writelines(liNames)
这会在with
块完成时自动关闭文件。