ValueError:关闭文件python上的I / O操作

时间:2015-02-26 16:21:26

标签: python

我对编程相对较新,我想创建一些Python代码,只需在特定的数字和字符序列上搜索并用点替换它们。它需要在大文件上运行。所以我想出了这个。

import re


f = open('filein.txt','r')
o = open ('fileout4.txt','w')

newdata=f.read()
rc=re.compile('(?<=..\d)[,]')
for line in newdata:
        newdataline=newdata
        newline = rc.sub('.',newdata)
        o.write(newline)
        f.close()
        o.close()
f.close()
o.close()

它似乎工作,但我仍然收到此错误消息。

  File "C:\Python34\replace comma to dot usingresubtestnewlinecharacter.py", line 12, in ?
    o.write(newline)
ValueError: I/O operation on closed file

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

从for循环中删除close语句

for line in newdata:
        newdataline=newdata
        newline = rc.sub('.',newdata)
        o.write(newline)    # This is fine, remove the next two close statements!

文件在第一次迭代中关闭!这就是为什么下次循环迭代时,你会得到错误。

- 您喜欢

for line in newdata:
        newdataline=newdata
        newline = rc.sub('.',newdata)
        o = open ('fileout4.txt','w') # Open the file inside the loop (I prefer 'a' instead of 'w')
        o.write(newline)            
        o.close()                     # Get rid of f.close()
f.close()
相关问题