2

Trying to extract all the zip files and giving the same name to the folder where all the files are gonna be. Looping through all the files in the folder and then looping through the lines within those files to write on a different text file.
This is my code so far:

#!usr/bin/env python3
import glob
import os
import zipfile

zip_files = glob.glob('*.zip')
for zip_filename in zip_files:
    dir_name = os.path.splitext(zip_filename)[0]
    os.mkdir(dir_name)
    zip_handler = zipfile.ZipFile(zip_filename, "r")
    zip_handler.extractall(dir_name)

path = dir_name
fOut = open("Output.txt", "w")

for filename in os.listdir(path):
    for line in filename.read().splitlines():
        print(line)
        fOut.write(line + "\n")
fOut.close()

This is the error that I encounter:

for line in filename.read().splitlines():
AttributeError: 'str' object has no attribute 'read'
Dharman
  • 30,962
  • 25
  • 85
  • 135
Anjil Dhamala
  • 1,544
  • 3
  • 18
  • 37
  • `filename` is a string. instead of `read()`ing the string, you need to open the file and then read it. – axblount Apr 02 '15 at 17:25

1 Answers1

2

You need to open the file and also join the path to the file, also using splitlines and then adding a newline to each line is a bit redundant:

path = dir_name
with open("Output.txt", "w") as fOut:    
    for filename in os.listdir(path):
        # join filename to path to avoid file not being found
        with open(os.path.join(path, filename)):
            for line in filename:
                fOut.write(line)

You should always use with to open your files as it will close them automatically. If the files are not large you can simply fOut.write(f.read()) and remove the loop.

You also set path = dir_name which means path will be set to whatever the last value of dir_name was in your first loop which may or may not be what you want. You can also use iglob to avoid creating a full list zip_files = glob.iglob('*.zip').

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321