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
# 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))
4条答案
按热度按时间5ktev3wc1#
原始测试.csv:
运行后:
(删除
0, ABC
)qyzbxkaa2#
在作为csv阅读器阅读csv文件后,next()将返回文件中的每一行,因此可以这样解决:
pengsaosao3#
如果CSV文件足够小,请将其读入内存,删除该行并将其写回。
这里不需要Pandas甚至
csv
模块。如果您的文件较大,不要将其全部读入内存,而是动态地将其过滤到第二个文件中,然后替换第一个文件:
pdtvr36n4#
你可以试试看。如果文件不是太大的话,它会起作用的