如何使用python程序替换现有excel csv文件中的值? [英] How can I replace a value in an existing excel csv file using a python program?
问题描述
如何使用python程序更新现有的 .csv
文件中的值。目前,文件被读入程序,但我需要能够使用我的程序更改此值,并对文件进行更改。我如何做到这一点?这是我的程序:
import csv
file = open(productcodes.csv,r)
for csv.reader(file):
print(row [1])$ b $ b
如何覆盖值 row [1]
?
pre> import csv
r = csv.reader(open('productcodes.csv'))
lines = [l for l in r]
for l in lines:
l [1] =new value
writer = csv.writer(open('productcodes.csv','w'))
writer.writerows线)
您不能真正替换现有文件中的值。相反,您需要:
- 读取现有文件
- >
- 写出新文件(覆盖现有文件)
How can I update a value in an existing .csv
file using a python program. At the moment the file is read into the program but I need to be able to change this value using my program, and for the change to be made to the file. How can I do this? This is my program:
import csv
file = open("productcodes.csv", "r")
for row in csv.reader(file):
print(row[1])
How can I override the value row[1]
?
import csv
r = csv.reader(open('productcodes.csv'))
lines = [l for l in r]
for l in lines:
l[1] = "new value"
writer = csv.writer(open('productcodes.csv', 'w'))
writer.writerows(lines)
You can't really replace values in the existing file. Instead, you need to:
- read in existing file
- alter file in memory
- write out new file(overwriting existing file)
这篇关于如何使用python程序替换现有excel csv文件中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!