【问题标题】:How to read chunk from middle of a long csv file using Python (200 GB+)如何使用 Python (200 GB+) 从长 csv 文件的中间读取块
【发布时间】:2021-07-13 06:09:10
【问题描述】:

我有一个大的 csv 文件,我正在阅读它。在进程中间内存已满,所以我想从它离开的地方重新开始。我知道哪个块但不知道如何直接去那个块。

这是我尝试过的。

# data is the txt file
reader = pd.read_csv(data , 
                     delimiter = "\t",
                     chunksize = 1000
                    )


# Please see the code below. When my last process broke, i was 154 so I think it should 
# start from 154000th line. This time I don't 
# plan to read whole file at once so I have an 
# end point at 160000

first = 154*1000
last = 160*1000

output_path = 'usa_hotspot_data_' + str(first) + '_' + str(last) + '.csv'
print("Output file: ", output_path)

try:
    os.remove(output_path)
except OSError:
    pass

# Read chunks and save to a new csv
for i,chunk in enumerate(reader):
    if (i >= first and i<=last) :
          < -- here I do something  -- > 
        # Progress Bar to keep track 
        if (i% 1000 == 0):
            print("#", end ='')

但是,这需要很长时间才能到达我想去的第 i 行。我怎样才能跳过它之前的阅读块并直接去那里?

【问题讨论】:

标签: python pandas csv large-data chunks


【解决方案1】:

pandas.read_csv

skiprows:要跳过的行号(0 索引)或要跳过的行数 (int) 在文件的开头。

您可以将此skirows 传递给read_csv,它的作用类似于偏移量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2015-01-24
    • 2013-04-23
    • 2022-01-25
    • 2010-12-08
    • 1970-01-01
    相关资源
    最近更新 更多