2016-12-13 82 views
0

我試圖讓下面的代碼讀取文件raw.txt,按行分割並將每行保存爲.txt文件。然後,我想將每個文本文件追加到splits.zip,並在追加後刪除它們,以便在完成該過程時剩下的唯一東西是splits.zip,然後可以將其移動到別處以解壓縮。在當前的代碼,我得到以下錯誤:創建文本文件,將它們附加到zip,然後刪除它們

Traceback (most recent call last): File "/Users/Simon/PycharmProjects/text-tools/file-splitter-txt.p‌​y", 
line 13, in <module> at stonehenge summoning the all father. z.write(new_file) 
File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framewo‌​rk/Versions/2.7/lib/‌​python2.7/zipfile.py‌​", line 1123, in write st = os.stat(filename) TypeError: coercing to Unicode: need string or buffer, 
file found 

我的代碼:

import zipfile 
import os 

z = zipfile.ZipFile("splits.zip", "w") 
count = 0 
with open('raw.txt','r') as infile: 
    for line in infile: 
     print line 
     count +=1 
     with open(str(count) + '.txt','w') as new_file: 
      new_file.write(str(line)) 
     z.write(new_file) 
     os.remove(new_file) 
+0

什麼是完整的回溯? –

+0

'追蹤(最近呼叫最後): 文件「/Users/Simon/PycharmProjects/text-tools/file-splitter-txt.py」,第13行,在 在巨石陣召喚所有的父親。 z.write(new_file) 文件「/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/zipfile.py」,第1123行,寫入 st = os.stat(文件名) TypeError:強制爲Unicode:需要字符串或緩衝區,找到文件 – textnet

回答

1

你可以簡單地使用writestr直接寫入字符串到壓縮文件。例如:

zf.writestr(str(count) + '.txt', str(line), compress_type=...) 
0

使用下面的文件名。 write方法預計文件名和remove需要路徑。但你已經給出了文件(file_name

z.write(str(count) + '.txt') 
os.remove(str(count) + '.txt') 
相關問題