Python子进程无法找到csv writer

时间:2016-03-27 19:35:54

标签: python bash csv subprocess gzip

我正在从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:file:没有这样的文件或目录”,尽管事实上1)文件是事先创建的,并且2)已经在目录中已经有了csv的副本运行,因为这是一个反复运行的脚本。

这些观点让我觉得python正在以某种方式捆绑文件而bash无法查看/访问它。关于如何让这个转换运行的任何想法?

由于

2 个答案:

答案 0 :(得分:4)

只需传递"file",gzip正在寻找一个名为csv_filename的文件,该文件不存在,因此错误不是subprocess.call(['gzip', csv_filename]) 文件:

file

gzip没有foreach参数,你只需要传递文件名。

答案 1 :(得分: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])