Simon Lindgren
Simon Lindgren

Reputation: 2041

Creating text files, appending them to zip, then delete them

I am trying to get the code below to read the file raw.txt, split it by lines and save every individual line as a .txt file. I then want to append every text file to splits.zip, and delete them after appending so that the only thing remaining when the process is done is the splits.zip, which can then be moved elsewhere to be unzipped. With the current code, I get the following error:

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

My code:

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)

Upvotes: 0

Views: 51

Answers (2)

Marlon Abeykoon
Marlon Abeykoon

Reputation: 12495

Use the file name like below. write method expects the filename and remove expects path. But you have given the file (file_name)

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

Upvotes: 0

Maurice Meyer
Maurice Meyer

Reputation: 18136

You could simply use writestr to write a string directly into the zipFile. For example:

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

Upvotes: 1

Related Questions