2013-01-23 76 views
14

我无法打开文件(amount2.csv)进行更改,保存并关闭文件。Python 2.7.1:如何打开,编辑和关闭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 (<>删除)

+1

这可能不是是错误的原因,但请看看你打开b标志,即'rb'而不是r。 csv.reader的文档说“如果csvfile是一个文件对象,它必须在平台上用'b'标志打开,这是有所作为的。”众所周知,它在Windows上有所作为。 –

回答

15

<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) 

要追加行到您的文件,而不是在Python CSV Docs

编辑做

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的最trobulesome线可能是

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 
+0

谢谢!我一直在阅读文档,但是对编程来说很陌生,并且在理解这些解释时遇到了一些麻烦。我遇到了以下警告:_csv.Error:在未加引号的字段中显示的换行符 - 是否需要以universal-newline模式打开文件? 我可以通过打开('amount2.csv','rU')作为f:“ – Sean

+0

[import csv with open('amount2.csv','rU')作为f: 阅读器= csv.reader(F) 在读者行: #行是字符串的列表 #使用的string.join把它们放在一起 打印 ''。加入(行) 变化= [ ['1打”, '12'], ] 张开( 'amount2.csv', 'WB')为f: 作家= csv.writer(F) writer.writerows(改变) F。close()]'code' – Sean

+0

我最终用'1打','12'擦除/替换csv文件的所有内容。我只想每次用'12'替换每个'1打'。 – Sean