如何使用python删除CSV文件的第一行?

lf5gs5x2  于 2023-02-10  发布在  Python
关注(0)|答案(4)|浏览(397)

我想使用Python只删除CSV的第一行(而不是标题)。
我尝试过很多使用csv模块或pandas的解决方案,但没有一个对我有效。所有的解决方案要么打印出csv文件,要么不修改原始文件。
重要的是,我不想打印或跳过/忽略第一行,我想删除它并将其保存到原始文件,而不是创建另一个文件。

5ktev3wc

5ktev3wc1#

FILENAME = 'test.csv'
DELETE_LINE_NUMBER = 1

with open(FILENAME) as f:
    data = f.read().splitlines() # Read csv file
with open(FILENAME, 'w') as g:
    g.write('\n'.join([data[:DELETE_LINE_NUMBER]] + data[DELETE_LINE_NUMBER+1:])) # Write to file

原始测试.csv:

ID, Name
0, ABC
1, DEF
2, GHI
3, JKL
4, MNO

运行后:

ID, Name
1, DEF
2, GHI
3, JKL
4, MNO

(删除0, ABC

qyzbxkaa

qyzbxkaa2#

在作为csv阅读器阅读csv文件后,next()将返回文件中的每一行,因此可以这样解决:

import csv
csv_file_name= '<your_file_name>.csv'

file = open(csv_file_name)
csvreader = csv.reader(file)

# store headers and rows
header = next(csvreader)

# ignore first row 
next(csvreader)

# store other rows
rows = []
for row in csvreader:
        rows.append(row)

file.close()

with open(csv_file_name, 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)

    # write multiple rows
    writer.writerows(rows)
pengsaosao

pengsaosao3#

如果CSV文件足够小,请将其读入内存,删除该行并将其写回。
这里不需要Pandas甚至csv模块。

# Read lines into list
with open("myfile.csv") as f:
    lines = list(f)

lines.pop(1)  # pop the second line out (assuming the zeroth line is headers)

# Write lines back into file
with open("myfile.csv", "w") as f:
    for line in lines:
        f.write(line)

如果您的文件较大,不要将其全部读入内存,而是动态地将其过滤到第二个文件中,然后替换第一个文件:

import os

with open("myfile.csv") as rf, open("myfile.csv.temp", "w") as wf:
    for i, line in enumerate(rf):
        if i != 1:  # Everything but the second line
            wf.write(line)

os.replace("myfile.csv.temp", "myfile.csv")
pdtvr36n

pdtvr36n4#

你可以试试看。如果文件不是太大的话,它会起作用的

# Read the data
with open("your file.csv", "r") as f:
    data = f.read().split("\n")

# Remove the 1st line
del data[1]

# Save the data
with open("your file.csv", "w") as f:
    f.write("\n".join(data))

相关问题