gpt4 book ai didi

python - 值错误: I/O operation on closed file python

转载 作者:行者123 更新时间:2023-12-01 04:49:34 27 4
gpt4 key购买 nike

我对编程比较陌生,我想创建一些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

有人可以帮忙吗?

最佳答案

从 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()

关于python - 值错误: I/O operation on closed file python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28747493/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com