16

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

如何打开文件编辑、保存和关闭它?

import csv

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

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

4

2 回答 2

23

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

您看到的不是错误,而是“打印 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)

Python CSV 文档中的更多信息

编辑:

一开始我误解了,你想在你的 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
于 2013-01-23T02:27:19.957 回答
0

您正在尝试打印文件对象本身,这不会有多大用处。您是否查看过 CSV 模块的文档?第一个代码示例向您展示了如何使用 csv.reader。

于 2013-01-23T02:21:24.127 回答