我只想洗掉 python 中 csv 的第一行(不是標題)我已經嘗試了許多使用 import csv 或 pandas 的解決方案,但還沒有對我有用。所有解決方案都列印出 csv 并且沒有修改原始檔案。
重要的是我不想列印或跳過/忽略第一行我想洗掉它并將其保存到原始檔案而不是創建另一個檔案。
謝謝:)
uj5u.com熱心網友回復:
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)
uj5u.com熱心網友回復:
如果您的(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")
uj5u.com熱心網友回復:
你可以試試。如果檔案不是太大,它可以作業
# 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))
uj5u.com熱心網友回復:
只需將標題名稱存盤在串列中,然后將 CSV 行存盤在串列串列中,其中每個串列都是一個行值。然后,您可以將這些值寫入具有相同檔案名的 CSV 檔案中。
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)
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/492549.html
