为什么我不能写入我在python中打开的文件?

dan*_*007 0 python

我打开python解释器并尝试写入我同时阅读的文件:

file = open("foo.txt")
lines = file.readlines()
for i in range(0, 3):
    file.write(lines[0])
Run Code Online (Sandbox Code Playgroud)

但是,python发出了一个错误,指出我在尝试执行时遇到了错误的文件处理程序file.write(lines[0]).为什么我不能将文件的第一行写入文件本身?

Lev*_*von 7

为了写入文件,必须以写入读/写模式打开文件

file = open("foo.txt", "r+")  # reading and writing to file
Run Code Online (Sandbox Code Playgroud)

要么

file = open("foo.txt", "w")   # writing only to file
Run Code Online (Sandbox Code Playgroud)

如果你打开一个文件并且没有指定一个模式,它默认处于读取模式,所以你打开了文件"read",但是试图"写"到它.

有关更多信息,请参阅阅读和编写文件 Python Docs.@Mizuho还建议了这个关于Python File IO的页面,它对各种可用模式有很好的总结.