到目前为止,这就是我要尝试的所有内容,说明该文件未打开?有什么基本方法可以解决此问题?

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()

最佳答案

在此行之后,具体说明评论的建议:

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上的文本文件尤其棘手。

07-25 20:25