2014-03-25 319 views
0

好了,所以,我必須分配在多個文件的file.txt的,這裏的代碼ValueError異常:在關閉的文件I/O操作

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

所以,如果我運行它,它給了我這個錯誤:

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

我明白,如果你的循環做一個文件被關閉,所以我試圖把f在for循環,但它不工作的原因不是得到的:

out1.txt 
1 
2 
3 
4 

out2.txt 
5 
6 
7 
8 

我只得到文件的最後一行。我應該怎麼做,有什麼辦法可以回想起我之前定義的開放函數?我是一個非常新的Python,所以我很抱歉,如果我問了一些我不能做的事,請耐心等待:D

回答

0

f.close()for循環內,然後不要open一個新的文件作爲f,從而對下一次迭代的錯誤。您還應該使用with來處理文件,這可以節省您需要明確地close他們。

當你想在同一時間給每個out文件中寫入四行,你可以做到這一點,如下所示:

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) 

請注意,我用的變量名,使它更清楚一點發生了什麼。

+0

感謝它的工作:D – Maxpnl

0

您關閉了文件,但是您不會從for循環中斷。

0

如果a == d您正在關閉f,然後稍後(在下一次迭代中)您正在嘗試寫入它,從而導致錯誤。
也 - 你爲什麼關閉f兩次?

0

你或許應該刪除第一個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() 
相關問題