Python如何同时读写一个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21773243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:35:18  来源:igfitidea点击:

Python how can read and write a file at same time

python

提问by Carl

f = open("test.txt",'r+')
print f.read();
f.write('\n\nI am carl wei.')
print f.read();
f.close()

but it's has a eeror:

但它有一个错误:

Traceback (most recent call last):
File "C:\Users\carl.wei\workspace\Python\FileTest.py", line 9, in f.write('\n\nI am carl wei.') IOError: [Errno 0] Error

回溯(最近一次调用):
文件“C:\Users\carl.wei\workspace\Python\FileTest.py”,第 9 行,在 f.write('\n\nI am carl wei.') IOError: [错误 0] 错误

回答by Prelude

I don't know I got your question or not, but if you want to read a file and write it at the same time, you may like to check out This

我不知道我有没有收到你的问题,但如果你想同时读一个文件和写它,你可能想看看这个

But from my experience if you use the same file to write and read datas all the data will be erased and that might be trouble some in future, ergo you can simply make another file in the same directory and have some code like this:

但是根据我的经验,如果您使用相同的文件来写入和读取数据,所有数据都将被删除,这在将来可能会带来麻烦,因此您可以简单地在同一目录中创建另一个文件并使用如下代码:

original_file= open('test.txt','r')# r when we only wanna read file
revised_file = open('test1.txt','w')# w when u wanna write sth on the file

for aline in original_file:

    revised_file.write('I am carl wei.\n' )#for writing your new data

original_file.close()
revised_file.close()