python批量处理csv文件画图,使用Python批量编辑csv文件

I need to edit several csv files. Actually, most of the files are fine as they are, it's just the last (41st) column that needs to be changed. For every occurrence of a particular string in that column, I need it to be replaced by a different string; specifically, every occurrence of 'S-D' needs to be replaced by 'S'. I've tried to accomplish this using Python, but I think I need to write the csv files and I'm not quite sure how to do this:

import os

import csv

path=os.getcwd()

filenames = os.listdir(path)

for filename in filenames:

if filename.endswith('.csv'):

r=csv.reader(open(filename))

for row in r:

if row[40] == "S-D":

row[40] = "S"

Any help? Also, if anyone has a quick , elegant way of doing this with a shell script, that would probably be very helpful to me as well.

解决方案

Be sure to read up on the Python documentation for the CSV File Reading and Writing. Lots to learn there. Here is a basic example based on your question. Only modifying the data in the last column, writing out a modified file with "_edited" in the name.

import os

import csv

path=os.getcwd()

filenames = os.listdir(path)

for filename in filenames:

if filename.endswith('.csv'):

r=csv.reader(open(filename))

new_data = []

for row in r:

row[-1] = row[-1].replace("S-D", "S")

new_data.append(row)

newfilename = "".join(filename.split(".csv")) + "_edited.csv"

with open(newfilename, "w") as f:

writer = csv.writer(f)

writer.writerows(new_data)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值