我需要删除我的csv文件的第二行。
我正在使用下面的代码,但遗憾的是它不起作用。
data = ""
adresse = "SLV.csv"
if os.path.exists(adresse) :
f = open(adresse,"ab")
writer = csv.writer(f,delimiter = ",")
reader = csv.reader(open(adresse,"rb") , delimiter = ",")
for line in reader:
if reader.line_num == 2:
writer.writerow(line)
f.close()
答案 0 :(得分:2)
由于你要做的只是删除第二行,使用csv模块是过度的。如果文件是逗号分隔数据或Vogon诗歌,则无关紧要。写下前面部分,跳过中间部分并写下结尾。
import shutil
# generate test file
with open('x.txt', 'w') as f:
for i in range(10):
f.write('line %d\n' % i)
# skip one line
with open('x.txt','rb') as rd, open('x.txt', 'rb+') as wr:
wr.write(rd.readline())
rd.readline()
shutil.copyfileobj(rd, wr)
wr.truncate()
print open('x.txt').read()
答案 1 :(得分:1)
写入临时文件并在以下后更新原始文件:
if os.path.exists(adresse) :
with open(adresse,"r") as f,open("temp.csv" "a+") as temp:
writer = csv.writer(temp,delimiter = ",")
reader = csv.reader(f , delimiter = ",")
for ind, line in enumerate(reader):
if ind == 2:
continue
else:
temp.writerow(line)
temp.seek(0)
with open(adresse,"w") as out:
reader = csv.reader(temp , delimiter = ",")
writer = csv.writer(out,delimiter = ",")
for row in reader:
writer.writerow(line)
如果可以将文件读入内存,只需在阅读器上调用列表并删除第二个元素:
if os.path.exists(adresse) :
with open(adresse,"r") as f:
reader = list(csv.reader(f , delimiter = ","))
reader.pop(1)
with open(adresse,"w") as out:
writer = csv.writer(out,delimiter = ",")
for row in reader:
writer.writerow(row)
答案 2 :(得分:0)
如果我理解正确您正在尝试制作新文件而您不想插入第2行。 如果这是您的情况,您的程序中存在一个微不足道的错误,即:
if reader.line_num != 2:
writer.writerow(line)
答案 3 :(得分:0)
这是我的解决方案,您可以编写更少的代码:
>>> import pyexcel as pe # pip install pyexcel
>>> sheet = pe.load("SLV.csv")
>>> del sheet.row[1] # first row starts at index 0
>>> sheet.save_as("SLV.csv")
答案 4 :(得分:0)
我同意tdelaney,这是一个更紧凑的解决方案
lines = open('x.txt', 'r').readlines()
lines.remove(1)
open('x.txt', 'w').writelines(lines)