创建文本文件,将它们附加到邮政编码,然后将其删除



我正在尝试获取下面的代码以读取文件raw.txt,用行分开,然后将每个单个行保存为.txt文件。然后,我想将每个文本文件附加到splits.zip,并在附加附加后删除它们,以便完成该过程完成后唯一剩下的是splits.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)

您可以简单地使用Writester将字符串直接写入Zipfile。例如:

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

使用如下所示的文件名。write方法期望文件名和remove期望路径。但是您给出了文件(file_name

z.write(str(count) + '.txt')
os.remove(str(count) + '.txt')

相关内容

最新更新