如何用python替换特定列的csv文件中的单词 [英] How to replace a word in a csv file in specific column with python

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

问题描述

美好的一天,

我尝试使用csv文件中的索引在特定列中更改单词,但未更改.

I tried to change a word in a certain column,using index, in a csv file ,but it is not changed.

我尝试使用的代码:

import csv

with open('INPUT.CSV', 'r') as file1, open('OUTPUT.csv','w',newline='') as file2:
   reader = csv.reader(file1, delimiter=',')
   writer = csv.writer(outfile, delimiter=',')

   for row in reader:
        row[0].replace('word','changed word')# I want to replace in first column=row[0] 'word' with 'changed word'
        writer.writerow(row)

输出文件与输入文件相同,未更改.

The output file is same with the input, no changed.

有人可以这样帮助我吗?非常感谢!

Can someboby help me in this way?Many thanks in advance!

推荐答案

一个工作示例会更好(输出以file2打开,但writer被赋予outfile)

A working example would be better (output is open as file2 but writer is given outfile)

但是无论如何,您的问题是replace

But in any case your problem is replace

  • replace返回字符串的副本(如果条件匹配,则替换为文本)
  • replace returns a copy of the string (with replaced text if the criteria matches)

但是您正在丢弃返回的值.您实际上在row[0]

But you are discarding the returned value. You are actually changing nothing in row[0]

解决方案:

replaced = row[0].replace('word','changed word')  # I want to replace in first column=row[0] 'word' with 'changed word'
row[0] = replaced
writer.writerow(row)

这篇关于如何用python替换特定列的csv文件中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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