[英]add a new line after a specific line of a csv file in python3
I am writing a python code in which a csv file is read and some information are written in. I should find one specific row and add a new line of data after it, at this stage. 我正在编写一个python代码,其中读取了一个csv文件并写入了一些信息。在这个阶段,我应该找到一个特定的行并在其后添加一行新的数据。 I have succeeded finding the row but I can not write the new line of data after it. 我已成功找到该行,但我无法在其后写入新的数据行。 Here is my attempt: 这是我的尝试:
file = open('db.csv', 'r+')
table = csv.reader(file)
for row in table:
if(row == ['tbl']):
file.seek(len(row)) #this part is the problem I suppose
break
table = csv.writer(file)
table.writerow(['1', '2'])
Using file.seek
/ file.tell
is tricky because csv.reader
could read ahead; 使用file.seek
/ file.tell
很棘手,因为csv.reader
可以提前读取; cannot tell exact file position that match current row. 无法确定与当前行匹配的确切文件位置。
Also inserting is not trivial; 插入也不是微不足道的; you need to remember remaing parts. 你需要记住剩余部分。
I would do it following way: 我会按照以下方式做到:
import csv
import shutil
with open('db.csv', 'r', newline='') as f, open('db.csv.temp', 'w', newline='') as fout:
reader = csv.reader(f)
writer = csv.writer(fout)
for row in reader:
writer.writerow(row)
if row == ['tbl']:
writer.writerow([]) # empty line
shutil.move('db.csv.temp', 'db.csv')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.