解压缩目录中的多个zip文件? [英] Unzipping multiple zip files in a directory?

查看:169
本文介绍了解压缩目录中的多个zip文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将目录中的多个文件解压缩并将其转换为csv文件. 文件在文件1.gz,2.gz,3.gz等中按顺序编号

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?

当前代码为

 #! /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()

当前计划是对每个目录中的.gz文件总数进行计数,并对每个文件使用循环来解压缩并打印出txt/csv.

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?

此外,python是否类似于perl,其中双引号解释了字符串?

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

推荐答案

为此,您几乎不需要Python:)

You hardly need Python for this :)

但是您可以在单个Python脚本中执行此操作.您需要使用:

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

  • 操作系统
  • os.path(可能)
  • gzip
  • glob(会为您提供一个不错的文件列表,例如glob("*.gz") )
  • os
  • os.path (possibly)
  • gzip
  • glob (will get your a nice glob listing of files. e.g: glob("*.gz"))

可以通过 https://docs.python.org/阅读这些模块,并去吧! :)

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

这篇关于解压缩目录中的多个zip文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆