python怎么关闭csv文件_Python 2.7.1:如何打开,编辑和关闭CSV文件

你看到的不是错误,而是你的“打印f”的结果.要看看你的文件的内容,你会做

with open('test.csv', 'rb') as f:

reader = csv.reader(f)

for row in reader:

# row is a list of strings

# use string.join to put them together

print ', '.join(row)

要将行附加到您的文件,而是

changes = [

['1 dozen','12'],

['1 banana','13'],

['1 dollar','elephant','heffalump'],

]

with open('test.csv', 'ab') as f:

writer = csv.writer(f)

writer.writerows(changes)

编辑:

首先我误解了,你想把csv文件中的’1打’的所有条目改成’12’.我会先说,这样做比较容易做,而不使用csv模块,但这里是一个使用它的解决方案.

import csv

new_rows = [] # a holder for our modified rows when we make them

changes = { # a dictionary of changes to make, find 'key' substitue with 'value'

'1 dozen' : '12', # I assume both 'key' and 'value' are strings

}

with open('test.csv', 'rb') as f:

reader = csv.reader(f) # pass the file to our csv reader

for row in reader: # iterate over the rows in the file

new_row = row # at first, just copy the row

for key, value in changes.items(): # iterate over 'changes' dictionary

new_row = [ x.replace(key, value) for x in new_row ] # make the substitutions

new_rows.append(new_row) # add the modified rows

with open('test.csv', 'wb') as f:

# Overwrite the old file with the modified rows

writer = csv.writer(f)

writer.writerows(new_rows)

如果你刚开始编程和python最麻烦的线路可能是

new_row = [ x.replace(key, value) for x in new_row ]

但这只是一个有效等同于列表的理解

temp = []

for x in new_row:

temp.append( x.replace(key, value) )

new_row = temp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值