【问题标题】:Python how can read and write a file at same time [duplicate]Python如何同时读取和写入文件[重复]
【发布时间】:2014-02-14 07:27:06
【问题描述】:
f = open("test.txt",'r+')
print f.read();
f.write('\n\nI am carl wei.')
print f.read();
f.close()

但它有一个eeror:

回溯(最近一次通话最后一次):
文件“C:\Users\carl.wei\workspace\Python\FileTest.py”,第 9 行,在 f.write('\n\n我是卡尔魏。') IOError: [Errno 0] 错误

【问题讨论】:

标签: python


【解决方案1】:

我不知道我有没有收到你的问题,但如果你想同时读取和写入文件,你可以查看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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多