Python 2.7.1:如何打开,编辑和关闭CSV文件

时间:2013-01-23 01:30:10

标签: python csv python-2.7

我无法打开文件(amount2.csv)进行更改,保存并关闭文件。

如何打开文件编辑,保存并关闭它?

import csv

changes = {
    '1 dozen' : '12'
    }
with open('amount2.csv', 'r') as f:
reader = csv.reader(f)
print f
f.close()

我的错误:打开文件'amount2.csv',模式'r'在0x1004656f0 (<>删除)

2 个答案:

答案 0 :(得分:20)

<open file 'amount2.csv', mode 'r' at 0x1004656f0>

您看到的不是错误,而是您打印的结果f&#39;。要改为查看文件内容,请执行

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)

Python CSV Docs

的更多信息

编辑:

我一开始误解了,你想要改变“打打”的所有条目。到&#39; 12&#39;在您的csv文件中。我首先要说的是,如果不使用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

答案 1 :(得分:0)

您正在尝试打印文件对象本身,这不会有用。 你看过the documentation for the CSV module了吗?第一个代码示例向您展示了如何使用csv.reader。