Appending to the end of a certain line

2019-08-31 09:46发布

问题:

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.