简体   繁体   English

为什么我无法写入在python中打开的文件?

[英]Why can't I write to a file that I open in python?

I opened the python interpreter and tried to write to a file I was reading at the same time: 我打开了python解释器,并尝试写入同时读取的文件:

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

However, python issued an error that noted I had a bad file handler when I tried to execute file.write(lines[0]) . 但是,python发出一个错误,指出我在尝试执行file.write(lines[0])时遇到错误的文件处理程序。 Why can't I write the first line of a file to the file itself? 为什么我不能将文件的第一行写到文件本身?

In order to write to a file, it's necessary to open the file in write or read/write mode 为了写入文件,必须以写入读取/写入模式打开文件

file = open("foo.txt", "r+")  # reading and writing to file

or 要么

file = open("foo.txt", "w")   # writing only to file

If you open a file and don't specify a mode, it's in read mode by default, so you had opened your file for "read", but were trying to "write" to it. 如果您打开文件但未指定模式,则默认情况下该文件处于读取模式,因此您已打开文件以进行“读取”,但试图对其进行“写入”。

See Reading and Writing Files Python Docs for more information. 有关更多信息,请参见读取和写入文件 Python Docs。 @Mizuho also suggested this page about Python File IO which has a very nice summary of the various modes available. @Mizuho还建议此页面有关Python File IO ,该页面对可用的各种模式进行了很好的总结。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM