Appending to the end of a certain line

依然范特西╮ 提交于 2019-12-12 06:14:08

问题


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.

Here's an example:

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?


回答1:


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)

My test.csv file at start:

key,value
a,1
b,2
c,3
d,4

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.



来源:https://stackoverflow.com/questions/30038916/appending-to-the-end-of-a-certain-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!