使用python更改CSV文件中的列的值 [英] Change values of a column in CSV file using python

查看:1159
本文介绍了使用python更改CSV文件中的列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,只需要一点帮助。

I am new to python and just need a small help.

我们有一个用管道分隔的CSV文件,看起来像这样

We have a Pipe delimited CSV file which looks like this

DATE|20160101
ID | Name | Address | City | State | Zip   | Phone | OPEID  | IPEDS |
10 | A... | 210 W.. | Mo.. | AL... | '31.. | 334.. | '01023 | 10063 |
20 | B... | 240 N.. | Ne.. | Ut... | '21.. | 335.. | '01024 | 10064 |

Zip和OPEID列的每个值开头都带有撇号

Every value of Zip and OPEID columns has apostrophes in the beginning

因此,我们希望创建一个新的CSV文件,其中从这2列的每个值中都删除了撇号。

So we wish to create a new CSV file where apostrophes are removed from each value of these 2 columns.

新文件应如下所示:

DATE|20160101
ID | Name | Address | City | State | Zip  | Phone | OPEID | IPEDS |
10 | A... | 210 W.. | Mo.. | AL... | 31.. | 334.. | 01023 | 10063 |
20 | B... | 240 N.. | Ne.. | Ut... | 21.. | 335.. | 01024 | 10064 |

此代码适用于复制数据而不会删除撇号

This code works for copying data without removing apostrophes

import os
import csv

file1 = "D:\CSV\File1.csv"
with open(file1, 'rb') as csvfile:

         reader = csv.reader(csvfile, delimiter = '|')

         path = "D:/CSV/New"
         if not os.path.exists(path):
             os.makedirs(path)

         writer = csv.writer(open(path+"File2"+".csv", 'wb'), delimiter = '|')

         for row in reader:
             writer.writerow(row)

csvfile.close()


推荐答案

它对我有用...尝试这个。

It worked for me... Try this.

res=[]
with open('hi.csv') as f:
    content=csv.reader(f,delimiter='|')
    for row in content:
        for str in range (len(row)):
            row[str]=row[str].replace('\'','')
        res.append(row)
    f.close()
with open('hi.csv','wb') as ff:  # python 3 => 'wb' => 'w',newline=''
    sw=csv.writer(ff,delimiter='|',quoting=csv.QUOTE_MINIMAL)
    for rows in res:
        sw.writerow(rows)
ff.close()

这篇关于使用python更改CSV文件中的列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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