簡體   English   中英

刪除大 CSV 文件的第一行?

[英]Removing first line of Big CSV file?

我應該如何在 python 中刪除一個大 CSV 文件的第一行? 我在這里查看了以前的解決方案,其中一個是:

with open("test.csv",'r') as f:
    with open("updated_test.csv",'w') as f1:
        f.next() # skip header line
        for line in f:
            f1.write(line)

這給了我這個錯誤:

f.next() # skip header line
AttributeError: '_io.TextIOWrapper' object has no attribute 'next'

另一個解決方案是:

with open('file.txt', 'r') as fin:
    data = fin.read().splitlines(True)
with open('file.txt', 'w') as fout:
    fout.writelines(data[1:])

這帶來了內存問題!

f.next()替換為next(f)

with open("test.csv",'r') as f, open("updated_test.csv",'w') as f1:
    next(f) # skip header line
    for line in f:
        f1.write(line)

使用f.__next__()而不是 f.next()

此處的文檔: https : //docs.python.org/3/library/stdtypes.html#iterator。 下一個

使用sed可能是最快的並且不需要臨時文件,因此 python 包裝器將是:

import subprocess

def delete_first_lines(filename, line_nums):
    n = '1,{}d'.format(line_nums)
    subprocess.Popen(['sed', '-i', n, filename ],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
        )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM