在 Python 2.7 中将.csv.gz转换为.csv



我已经阅读了有关SO和其他不同地方的文档和一些其他帖子,但我不太清楚这个概念:

当您调用csvFilename = gzip.open(filename, 'rb')然后reader = csv.reader(open(csvFilename))时,reader不是有效的csv文件吗?

我正在尝试解决下面概述的问题,并在第 41 行和第 7 行(下面突出显示(出现coercing to Unicode: need string or buffer, GzipFile found错误,导致我相信 gzip.open 和 csv.reader 不像我以前想象的那样工作。

我正在尝试解决的问题

我正在尝试获取results.csv.gz并将其转换为results.csv,以便我可以将results.csv转换为python字典,然后将其与另一个python字典组合在一起。

文件 1:

alertFile = payload.get('results_file')
alertDataCSV = rh.dataToDict(alertFile) # LINE 41
alertDataTotal = rh.mergeTwoDicts(splunkParams, alertDataCSV)

调用文件 2:

import gzip
import csv
def dataToDict(filename):
csvFilename = gzip.open(filename, 'rb')
reader = csv.reader(open(csvFilename)) # LINE 7
alertData={}
for row in reader:
alertData[row[0]]=row[1:]
return alertData
def mergeTwoDicts(dictA, dictB):
dictC = dictA.copy()
dictC.update(dictB)
return dictC

*编辑:也原谅我在 Python 中的非 PEP 命名风格

gzip.open返回一个类似文件的对象(与普通open返回的对象相同(,而不是解压缩文件的名称。只需将结果直接传递给csv.reader即可工作(csv.reader将接收解压缩的行(。 不过csv确实需要文本,所以在 Python 3 上你需要打开它才能作为文本读取(在 Python 2 上'rb'很好,该模块不处理编码,但是,csv模块也不处理(。只需更改:

csvFilename = gzip.open(filename, 'rb')
reader = csv.reader(open(csvFilename))

自:

# Python 2
csvFile = gzip.open(filename, 'rb')
reader = csv.reader(csvFile)  # No reopening involved
# Python 3
csvFile = gzip.open(filename, 'rt', newline='')  # Open in text mode, not binary, no line ending translation
reader = csv.reader(csvFile)  # No reopening involved

以下内容对我python==3.7.9有用:

import gzip
my_filename = my_compressed_file.csv.gz
with gzip.open(my_filename, 'rt') as gz_file:
data = gz_file.read() # read decompressed data
with open(my_filename[:-3], 'wt') as out_file:
out_file.write(data) # write decompressed data

my_filename[:-3] 是获取实际文件名,以便它确实获得一个随机文件名。

最新更新