使用Python批量编辑csv文件 [英] Batch editing of csv files with Python

查看:381
本文介绍了使用Python批量编辑csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编辑几个csv文件.实际上,大多数文件都可以正常使用,它只是需要更改的最后一列(第41列).对于该列中每次出现的特定字符串,我都需要将其替换为其他字符串;具体而言,每次出现的"S-D"都需要替换为"S".我尝试使用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"

有帮助吗?另外,如果任何人都可以使用Shell脚本快速,优雅地完成此任务,那对我也可能会很有帮助.

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)

这篇关于使用Python批量编辑csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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