Tom365
Tom365

Reputation: 7

ValueError: I/O operation on closed file python

i'm relatively new to programing and i wanted to create a bit of Python code that simply searches for , and replaces them with a dot, on certain number and character sequences. it needs to run on large files. so i came up with this.

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

it appears to work , but i still get this error message.

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

can anyone help here?

Upvotes: 1

Views: 214

Answers (1)

Bhargav Rao
Bhargav Rao

Reputation: 52071

Remove the close statements from the for loop

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

The files are closed in the first iteration itself! That's why the next time the loop iterates, you will get the error.

Or - As you prefer to do

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

Upvotes: 2

Related Questions