Python 子进程找不到 csv 写入器的输出
Python subprocess can't find the output of csv writer
我正在从 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: No such file or directory," 尽管 1) 文件是事先立即创建的,并且 2) 在之前的目录中已经有一个 csv 的副本运行,因为这是一个重复获取 运行 的脚本。
这些观点让我认为 python 以某种方式占用了文件,而 bash 不能 see/access。关于如何将此转换为 运行 的任何想法?
谢谢
只需传递 csv_filename
,gzip 正在寻找一个名为 "file"
的文件,该文件不存在,因此它不会出错 csv_filename
文件:
subprocess.call(['gzip', csv_filename])
gzip 没有 file
参数,您只需传递文件名即可。
您已经找到问题的正确答案....但是,您也可以使用 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])