简体   繁体   中英

Unzipping multiple zip files in a directory?

I need to unzip multiple files within a directory and convert them to a csv file. The files are numbered in order within the file, 1.gz, 2.gz, 3.gz etc

Can this be done within a single script or do I have to do it manually?

edit: current code is

 #! /usr/local/bin/python

import gzip
import csv
import os

f = gzip.open('1.gz', 'rb')
file_content = f.read()
filename = '1.txt'
target = open ('1.txt', 'w')
target.write(file_content)
target.close()
filename = '1.csv'
txt_file = '1.txt'
csv_file = '1.csv'
in_txt = csv.reader(open(txt_file, "rb"), delimiter = '\t')
out_csv = csv.writer(open(csv_file, 'wb'))
out_csv.writerows(in_txt)
dirname = '/home/user/Desktop'
filename = "1.txt"
pathname = os.path.abspath(os.path.join(dirname, filename))
if pathname.startswith(dirname):
os.remove(pathname)
f.close()

Current plan is to do a count for the total number of .gz files per directory and use a loop for each file to unzip and print the txt/csv out.

Is it feasible or is there a better way to this?

Also, is python similar to perl in which the double quotes interpretes the string?

You hardly need Python for this :)

But you can do this in a single Python script. You'll need to use:

  • os
  • os.path ( possibly )
  • gzip
  • glob ( will get your a nice glob listing of files. eg: glob("*.gz") )

Have a read up on these modules over at https://docs.python.org/ and have a go! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM