附加到某一行的端部 [英] Appending to the end of a certain line
问题描述
而不是附加到文件的结尾,我想追加到.csv文件的某行的末尾。
我想,当用户输入该.csv的第一列相匹配的输入来做到这一点。
Rather than appending to the end of a file, I am trying to append to the end of a certain line of a .csv file. I want to do this when the user enters an input that matches the first column of the .csv.
下面是一个例子:
file=open("class"+classno+".csv", "r+")
writer=csv.writer(file)
data=csv.reader(file)
for row in data:
if input == row[0]:
(APPEND variable TO ROW)
file.close()
有没有办法做到这一点?将我必须重新定义于是重写文件?
Is there a way to do this? Would I have to redefine and then rewrite the file?
推荐答案
您可以读取整个文件,然后更改需要更改和写回文件(这不是真的回写时,它的完整覆盖)的东西。
You can read the whole file then change what you need to change and write it back to file (it's not really writing back when it's complete overwriting).
也许这个例子可以帮助:
Maybe this example will help:
read_data = []
with open('test.csv', 'r') as f:
for line in f:
read_data.append(line)
with open('test.csv', 'w') as f:
for line in read_data:
key,value = line.split(',')
new_line = line
if key == 'b':
value = value.strip() + 'added\n'
new_line = ','.join([key,value])
f.write(new_line)
在启动
我的 test.csv
文件:
key,value
a,1
b,2
c,3
d,4
后,我运行的样本code:
And after I run that sample code:
key,value
a,1
b,2added
c,3
d,4
这可能不是大文件的最佳解决方案。
It's probably not the best solution with big files.
这篇关于附加到某一行的端部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!