【问题标题】:Loop through multiple levels of subfolders and convert csv.gz files to csv循环遍历多个级别的子文件夹并将 csv.gz 文件转换为 csv
【发布时间】:2018-12-24 06:15:19
【问题描述】:

我有数以千计的 csv.gz 文件,这些文件排列在多个级别的文件夹和子文件夹中。文件排列的快照是:

“文件夹”-“子文件夹 1”-“子文件夹 2”-“csv.gz 文件”

我想设置遍历每个文件夹和子文件夹的代码,并在保留 csv.gz 文件的同时提取 csv 文件。

我试过以下代码:

import gzip    
import os

directory = os.getcwd()

for dirpath, dir, files in os.walk(top=directory):
    for file in files:
        with gzip.open(file, 'rt') as f:
            data = f.read()
    with open(file[:-3], 'wt') as f:
      f.write(data) 

但是,我收到以下错误消息:“OSError: Not a gzipped file (b'{\n')”。有谁知道我为什么会收到此错误,或者是否有其他方法可以解压缩这些文件?我对编码很陌生,Python 是我尝试使用的第一种语言,因此非常感谢任何帮助。

【问题讨论】:

  • 你是在windows还是linux?如果是 linux,你可以做一个 find -name '*.gz' | xargs gunzip
  • 我在 linux 上。我刚刚尝试了该命令,但“*.gz”返回了无效的语法错误。
  • 这很奇怪!我测试时它正在工作。您可以发布find -name '*.gz' 的(截断)输出吗?如果这也不起作用,只是 find 的输出。
  • 对不起,我使用“find -name '*.gz'”得到了同样的错误,当我尝试“find”时,它返回错误:“NameError: name 'find' is not defined。 "我应该安装某种软件包吗?
  • 啊,你是在 python 中运行它吗?这些只是linux命令。所以打开一个终端和cd 到你的目录。然后在终端发出这些命令。我只是在回答您关于是否有其他方法可以解压缩这些文件的问题。

标签: python csv jupyter


【解决方案1】:

可能使用 Linux 命令是更简单的方法。试试下面的

find <your directory path here> -name '*.gz' | xargs gunzip

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-14
    • 2019-04-11
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2020-05-08
    • 1970-01-01
    相关资源
    最近更新 更多