如何使用Windows从tar文件读取特定文件?

问题描述

我有一个tar文件,其中压缩了几个文件。我需要使用熊猫读取一个特定的文件(格式为csv)。我尝试使用以下代码

import tarfile
tar = tarfile.open('my_files.tar','r:gz')
f = tar.extractfile('some_files/need_to_be_read.csv')

import pandas as pd
df = pd.read_csv(f.read())

但是会引发以下错误

OSError: Expected file path name or file-like object,got <class 'bytes'> type
代码的最后一行上的

。我该如何读取此文件

解决方法

调用pandas.read_csv()时,需要给它一个文件名或类似文件的对象。 tar.extractfile()返回类似文件的对象。不必将文件读入内存,而是将文件传递给Pandas。

因此,删除.read()部分:

import tarfile
tar = tarfile.open('my_files.tar','r:gz')
f = tar.extractfile('some_files/need_to_be_read.csv')

import pandas as pd
df = pd.read_csv(f)