附加到某一行的末尾 [英] Appending to the end of a certain line

查看:32
本文介绍了附加到某一行的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是附加到文件末尾,而是尝试附加到 .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

在我运行该示例代码之后:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆