Maxpnl
Maxpnl

Reputation: 98

"ValueError: I/O operation on closed file" while writing to a file in a loop

I have to divide a file.txt into more files. Here's the code:

a = 0
b = open("sorgente.txt", "r")
c = 5
d = 16 // c
e = 1
f = open("out"+str(e)+".txt", "w")
for line in b:
    a += 1
    f.writelines(line)
    if a == d:
        e += 1
        a = 0
        f.close()
f.close()

So , if i run it it gives me this error :

todoController\WordlistSplitter.py", line 9, in <module>
    f.writelines(line)
ValueError: I/O operation on closed file

I understood that if you do a for loop the file gets closed so I tried to put the f in the for loop but it doesn't work because instead of getting:

out1.txt
 1
 2
 3
 4

out2.txt
 5
 6
 7
 8

I get only the last line of the file. What should I do? Are there any way I can recall the open function I defined earlier?

Upvotes: 0

Views: 2533

Answers (4)

jonrsharpe
jonrsharpe

Reputation: 122052

You f.close() inside the for loop, then do not open a new file as f, hence the error on the next iteration. You should also use with to handle files, which saves you needing to explicitly close them.

As you want to write four lines at a time to each out file, you can do this as follows:

file_num = 0
with open("sorgente.txt") as in_file:
    for line_num, line in enumerate(in_file):
        if not line_num % 4:
            file_num += 1
        with open("out{0}.txt".format(file_num), "a") as out_file:
            out_file.writelines(line)

Note that I have used variable names to make it a bit clearer what is happening.

Upvotes: 1

Germano
Germano

Reputation: 2482

You should probably remove the first f.close():

a = 0
b = open("sorgente.txt", "r")
c = 5
d = 16 // c
e = 1
f = open("out"+str(e)+".txt", "w")
for line in b:
    a += 1
    f.writelines(line)
    if a == d:
        e += 1
        a = 0
        # f.close()
f.close()

Upvotes: 0

Itay Karo
Itay Karo

Reputation: 18286

if a == d you are closing f and then later (in the next iteration) you are trying to write to it which causes the error.
also - why are you closing f twice?

Upvotes: 0

aisbaa
aisbaa

Reputation: 10633

You close the file but you don't break from for loop.

Upvotes: 0

Related Questions