【问题标题】:Python subprocess can't find the output of csv writerPython子进程找不到csv writer的输出
【发布时间】:2016-07-15 02:04:16
【问题描述】:

我正在从 Mongo 中提取一些数据,通过 Python 对其进行清理,然后将其写入文本文件以导入 Vertica。 Vertica 无法解析 python 编写的 gzip(不知道为什么),所以我尝试将数据写入 csv 并使用 bash 来 gzip 文件。

csv_filename = '/home/deploy/tablecopy/{0}.csv'.format(vertica_table)

with open(csv_filename, 'wb') as csv_file:
    csv_writer = csv.writer(csv_file, delimiter=',')

    for replacement in mongo_object.find():
        replacement_id = clean_value(replacement, "_id")
        csv_writer.writerow([replacement_id, booking_id, style, added_ts])

subprocess.call(['gzip', 'file', csv_filename])

当我运行此代码时,我得到“gzip:文件:没有这样的文件或目录”,尽管事实上 1) 文件是事先立即创建的,并且 2) 之前的目录中已经有 csv 的副本运行,因为这是一个反复运行的脚本。

这些点让我认为 python 正在以某种方式绑定文件,而 bash 无法看到/访问它。关于如何运行此转换的任何想法?

谢谢

【问题讨论】:

    标签: python bash csv subprocess gzip


    【解决方案1】:

    您已经得到了问题的正确答案....但是,您也可以在编写时使用gzip 模块进行压缩,因此根本不需要调用gzip 程序。此示例假设您使用 python 3.x,并且您只有 ascii 文本。

    import gzip
    
    csv_filename = '/home/deploy/tablecopy/{0}.csv'.format(vertica_table)
    
    with gzip.open(csv_filename + '.gz', 'wt', encoding='ascii', newline='') as csv_file:
        csv_writer = csv.writer(csv_file, delimiter=',')
        for replacement in mongo_object.find():
            replacement_id = clean_value(replacement, "_id")
            csv_writer.writerow([replacement_id, booking_id, style, added_ts])
    

    【讨论】:

    • 当我使用 gzip 模块时,vertica 无法从文件中读取数据。这是一个单独的问题,可能值得提出自己的问题
    【解决方案2】:

    只需传递csv_filename,gzip 正在寻找一个名为"file" 的文件,该文件不存在,因此错误不是csv_filename 文件:

    subprocess.call(['gzip',  csv_filename])
    

    gzip 没有file 参数,您只需传递文件名。

    【讨论】:

      猜你喜欢
      • 2011-08-29
      • 2014-10-02
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      相关资源
      最近更新 更多