【问题标题】:Read multiple lines of csv file and delete these lines读取多行csv文件并删除这些行
【发布时间】:2021-09-07 04:36:27
【问题描述】:

我给了一个任务来读取特定的 n 行数据(CSV 文件)并删除它们。假设给定用户的时间戳、年龄、性别(CSV 格式),我想阅读 10 行以避免超载。但我不知道该怎么做。你能建议我如何有效地解决这个问题吗?谢谢

【问题讨论】:

标签: python python-3.x readline yield


【解决方案1】:
import csv
import pandas as pd

# reads your file in chunks (lines of 10)
chunk_iterator = pd.read_csv('sample.csv', chunksize=10)

# rewrite over file to 'delete' the unwanted lines
with open('sample.csv', 'w') as outf:
    writer = csv.writer(outf)
    for line in chunk_iterator:
        # if condition satisfied, write to new file
        if (<insert condition>):
            writer.writerow(line)

上面使用pandas 有效地以块的形式读取 csv 文件。然后它重写同一个文件,从而“删除”不满足您设置的特定条件的行。 (你没有具体说明这个条件是什么,所以不包括在内)。

如果您想保留原始文件并将输出写入不同的文件,请更改 outfile 行中的文件名,例如:with open('updated_sample.csv', 'w') as outf:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 2019-06-19
    • 2014-11-12
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 2014-12-10
    相关资源
    最近更新 更多