如何使用python程序替换现有excel csv文件中的值? [英] How can I replace a value in an existing excel csv file using a python program?

查看:1440
本文介绍了如何使用python程序替换现有excel csv文件中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用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线)

您不能真正替换现有文件中的值。相反,您需要:


  1. 读取现有文件

  2. >
  3. 写出新文件(覆盖现有文件)


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:

  1. read in existing file
  2. alter file in memory
  3. write out new file(overwriting existing file)

这篇关于如何使用python程序替换现有excel csv文件中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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