2013-01-23 73 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