我正在尝试获取下面的代码来读取文件raw.txt
,按行拆分并将每一行保存为.txt
文件。然后我想将每个文本文件附加到splits.zip
,并在追加后删除它们,以便在完成该过程时唯一剩下的就是splits.zip
,然后可以将其移动到其他位置以进行解压缩。使用当前代码,我收到以下错误:
Traceback (most recent call last): File "/Users/Simon/PycharmProjects/text-tools/file-splitter-txt.py",
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.framework/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 :(得分:1)
您只需使用writestr将字符串直接写入zipFile即可。例如:
zf.writestr(str(count) + '.txt', str(line), compress_type=...)
答案 1 :(得分:0)
使用如下文件名。 write
方法需要文件名和remove
期望路径。但是你已经给出了文件(file_name
)
z.write(str(count) + '.txt')
os.remove(str(count) + '.txt')