2016-12-13 83 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') 
相关问题