读取压缩的 csv 并添加新行

问题描述 投票:0回答:1

我有一个 zip 文件 t.zip,其中包含两个 csv 文件。第一个是 s.csv (30kB),另一个是 p.csv (60GB)。

我现在正在做的是将 p.csv 解压缩到磁盘,读取倒数第二行,执行一些逻辑,然后向 p.csv 添加新行。之后我再次压缩文件。

有更好的方法吗?没有解压到磁盘再压缩的东西吗?

我正在使用 Python 3.12 和 Pandas。

非常感谢!

python pandas zip python-zipfile
1个回答
0
投票

您无需解压缩文件并再次压缩即可实现此目的。但这会打开你的内存或RAM。因此,如果您的 RAM 不足或有许多用户同时更改内容,请不要使用此方法。

import zipfile
import pandas as pd
from io import BytesIO

# Load the zip file
with zipfile.ZipFile('t.zip', 'r') as zip_ref:
    # Extract p.csv to memory
    with zip_ref.open('p.csv') as csv_file:
        # Load the CSV file into a pandas DataFrame
        df = pd.read_csv(csv_file)

# Your logic here
# For example, get the second last row
second_last_row = df.iloc[-2]
# Add new lines to the DataFrame
new_data = '...'
# Append new lines to the DataFrame
df = df.append(new_data, ignore_index=True)

# Write the modified DataFrame back to memory
modified_csv = BytesIO()
df.to_csv(modified_csv, index=False)

# Update the zip file with the modified p.csv
with zipfile.ZipFile('t.zip', 'a') as zip_ref:
    zip_ref.writestr('p.csv', modified_csv.getvalue())
© www.soinside.com 2019 - 2024. All rights reserved.