[英]How to delete first row in a csv file using python
我只想刪除 python 中 csv 的第一行(不是標題)我已經嘗試了許多使用 import csv 或 pandas 的解決方案,但還沒有對我有用。 所有解決方案都打印出 csv 並且沒有修改原始文件。
重要的是我不想打印或跳過/忽略第一行我想刪除它並將其保存到原始文件而不是創建另一個文件。
謝謝:)
用csv reader讀取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)
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
原始 test.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
)
如果您的(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")
你可以試試。 如果文件不是太大,它可以工作
# 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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.