Python3在tar文件中使用csv文件

时间:2017-04-18 07:46:43

标签: python python-3.x csv tar

我正在尝试使用tar.gz文件中包含的csv文件,并且在将正确的数据/对象传递给csv模块时遇到问题。

假设我有一个tar.gz文件,其中包含许多csv文件,如下所示。

1079,SAMPLE_A,GROUP,001,,2017/02/15 22:57:30
1041,SAMPLE_B,GROUP,023,,2017/02/15 22:57:26
1077,SAMPLE_C,GROUP,005,,2017/02/15 22:57:31
1079,SAMPLE_A,GROUP,128,,2017/02/15 22:57:38

我希望能够访问内存中的每个csv文件,而无需从tar文件中提取每个文件并将其写入磁盘。 例如:

import tarfile
import csv

tar = tarfile.open("tar-file.tar.gz")

for member in tar.getmembers():
    f = tar.extractfile(member).read()
    content = csv.reader(f)
    for row in content:
        print(row)
tar.close()

这会产生以下错误。

    for row in content:
_csv.Error: iterator should return strings, not int (did you open the file in text mode?)

我也尝试将f解析为字符串,如csv模块文档中所述。

content = csv.reader([f])

以上产生同样的错误。

我尝试将文件对象f解析为ascii。

f = tar.extractfile(member).read().decode('ascii')

但是这会迭代每个csv元素,而不是迭代包含元素列表的行。

['1']
['0']
['7']
['9']
['', '']
['S']
['A']
['M']
['P']
['L']
['E']
['_']
['A']
['', '']
['G']
['R']

...剪断

['2']
['0']
['1']
['7']
['/']
['0']
['2']
['/']
['1']
['5']
[' ']
['2']
['2']
[':']
['5']
['7']
[':']
['3']
['8']
[]
[]

尝试将f解析为ascii并将其作为字符串

读取
f = tar.extractfile(member).read().decode('ascii')
content = csv.reader([f])

产生以下输出

    for row in content:
_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

为了演示不同的输出,我使用了以下代码。

import tarfile
import csv

tar = tarfile.open("tar-file.tar.gz")

for member in tar.getmembers():
    f = tar.extractfile(member).read()
    print(member.name)
    print('Raw :', type(f))
    print(f)
    print()
    f = f.decode('ascii')
    print('ASCII:', type(f))
    print(f)
tar.close()

这会产生以下输出。 (每个csv包含此示例的相同数据)。

./raw_data/csv-file1.csv
Raw : <class 'bytes'>
b'1079,SAMPLE_A,GROUP,001,,2017/02/15 22:57:30\n1041,SAMPLE_B,GROUP,023,,2017/02/15 22:57:26\n1077,SAMPLE_C,GROUP,005,,2017/02/15 22:57:31\n1079,SAMPLE_A,GROUP,128,,2017/02/15 22:57:38\n\n'

ASCII: <class 'str'>
1079,SAMPLE_A,GROUP,001,,2017/02/15 22:57:30
1041,SAMPLE_B,GROUP,023,,2017/02/15 22:57:26
1077,SAMPLE_C,GROUP,005,,2017/02/15 22:57:31
1079,SAMPLE_A,GROUP,128,,2017/02/15 22:57:38


./raw_data/csv-file2.csv
Raw : <class 'bytes'>
b'1079,SAMPLE_A,GROUP,001,,2017/02/15 22:57:30\n1041,SAMPLE_B,GROUP,023,,2017/02/15 22:57:26\n1077,SAMPLE_C,GROUP,005,,2017/02/15 22:57:31\n1079,SAMPLE_A,GROUP,128,,2017/02/15 22:57:38\n\n'

ASCII: <class 'str'>
1079,SAMPLE_A,GROUP,001,,2017/02/15 22:57:30
1041,SAMPLE_B,GROUP,023,,2017/02/15 22:57:26
1077,SAMPLE_C,GROUP,005,,2017/02/15 22:57:31
1079,SAMPLE_A,GROUP,128,,2017/02/15 22:57:38


./raw_data/csv-file3.csv
Raw : <class 'bytes'>
b'1079,SAMPLE_A,GROUP,001,,2017/02/15 22:57:30\n1041,SAMPLE_B,GROUP,023,,2017/02/15 22:57:26\n1077,SAMPLE_C,GROUP,005,,2017/02/15 22:57:31\n1079,SAMPLE_A,GROUP,128,,2017/02/15 22:57:38\n\n'

ASCII: <class 'str'>
1079,SAMPLE_A,GROUP,001,,2017/02/15 22:57:30
1041,SAMPLE_B,GROUP,023,,2017/02/15 22:57:26
1077,SAMPLE_C,GROUP,005,,2017/02/15 22:57:31
1079,SAMPLE_A,GROUP,128,,2017/02/15 22:57:38

如何让csv模块正确读取tar模块提供的内存中的文件? 感谢。

2 个答案:

答案 0 :(得分:2)

您只需使用io.StringIO()生成类似于csv库的对象文件即可使用。例如:

import tarfile
import csv
import io

with tarfile.open('input.rar') as tar:
    for member in tar:
        if member.isreg():      # Is it a regular file?
            print("{} - {} bytes".format(member.name, member.size))
            csv_file = io.StringIO(tar.extractfile(member).read().decode('ascii'))

            for row in csv.reader(csv_file):
                print(row)

答案 1 :(得分:0)

这个问题将近3年了。请注意,在简短讨论之后,可以在python: use CSV reader with single file extracted from tarfile中找到更好的解决方案:


import tarfile
import csv
import io

with tarfile.open('input.rar') as tar:
    for member in tar:
        if member.isreg():      # Is it a regular file?
            print("{} - {} bytes".format(member.name, member.size))
            csv_file = io.TextIOWrapper(tar.extractfile(member), encoding="utf-8")

            for row in csv.reader(csv_file):
                print(row)

TextIOWrapper对于较大的文件将具有更好的性能,因为它不需要立即使用一个完整的文件。相反,执行tar.extractfile(member).read()时,会将完整的成员文件加载到内存中。