Python如何在同一时间读写文件

2024-05-15 01:03:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但它有一个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


Tags: testtxtmostclosereadopenamwrite
1条回答
网友
1楼 · 发布于 2024-05-15 01:03:14

我不知道我有没有你的问题,但是如果你想同时读和写一个文件,你可能想看看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()

相关问题 更多 >

    热门问题