如何在Python中编辑CSV的整个字段值?

时间:2016-09-15 23:24:14

标签: python csv

我正试图像这样操纵CSV数据

ID,val1,val2,data1,val3,val4
BIGINT,BOOL,INT,VARCHAR,INT,BIGINT
10000,'F',1,'batman',1,0
20000,'T',0,'robin',1,1
30000,'T',1,'joker',0,1

ID,val1,val2,data1,val3,val4
BIGINT,BOOL,BOOL,VARCHAR,BOOL,BIGINT
10000,'F','T','batman','T',0
20000,'T','F','robin','T',1
30000,'T','T','joker','F',1

我编写了代码,它在编辑后将行打印为列表,但不知何故没有将其正确写入文件。我可以帮助我在这里做错吗?

index_list=[]

with open('input.csv') as fr:
                reader = csv.reader(fr)
                reader.next()
                reader.next()
                column_type=(reader.next())
                for index,val in enumerate(column_type):
                        if val=='INT':
                                index_list.append(index)

#this prints the list of fields where change to go
print(index_list)

with open('input.csv', 'rb') as f:
    reader1 = csv.reader(f) 
    reader1.next()
    reader1.next()
    with open('out.csv', 'wb') as fr:
        for row in reader1:
                for key in index_list: 
                        if row[key]==1:
                                row[key]='T'
                        elif row[key]==0:
                                row[key]='F'

                #this row prints correct data
                print(row)


         writer = csv.writer(fr)
         writer.writerows(row)

2 个答案:

答案 0 :(得分:0)

看起来你的缩进对于write语句来说是错误的。

with open('input.csv', 'rb') as f:
    reader1 = csv.reader(f) 
    reader1.next()
    reader1.next()
    with open('test.csv', 'wb') as fr:
        for row in reader1:
            for key in index_list: 
                if row[key]=='1':
                    row[key]='T'
                elif row[key]=='0':
                    row[key]='F'

                #this row prints correct data
                print(row)


             writer = csv.writer(fr)
             writer.writerows(row)

答案 1 :(得分:0)

您可以使用pandas并根据需要替换所有值。它看起来像是:

from StringIO import StringIO
import pandas as pd

TESTDATA = StringIO("""BIGINT,BOOL,INT,VARCHAR,INT
                    10000,'F',1,'batman',1
                    20000,'T',0,'robin',1
                    30000,'T',1,'joker',0""")


df = pd.read_csv(TESTDATA, sep=",", engine='python')
for column in df:
    if "int" in column.lower():
        df[column] = df[column].replace([1], 'T')
        df[column] = df[column].replace([0], 'F')

返回:

    BIGINT  BOOL    INT  VARCHAR    INT.1
0   10000   'F'     T    'batman'   T
1   20000   'T'     F    'robin'    T
2   30000   'T'     T    'joker'    F

之后,您可以将其保存回CSV文件