2013-01-13 44 views
1

如何使用Python 2.7更改某個單元格中的值?創建數據庫是最好的方法嗎? (變更 '1打' 至12兩次 - 每次 '1打' 被發現它被替換爲12)使用python更改csv中的單元格

輸入:

['item', 'amount', 'size', 'price'] 
['apple', '1 dozen', '3', '8'] 
['cherry', '84', '100 g', '3.5'] 
['orange', '1 dozen', '3', '9'] 

希望的輸出:

['item', 'amount', 'size', 'price'] 
['apple', '12', '3', '8'] 
['cherry', '84', '100 g', '3.5'] 
['orange', '12', '3', '9'] 

回答

0

假設您的輸入是amounts.csv,您可以嘗試以下操作:

import csv 

# Keep a dictionary of the changes you want to make 
changes = { 
    '1 dozen': 12 
    } 

with open('amounts.csv', 'rb') as f: 
    reader = csv.reader(f) 

    # Iterating through the list of lists 
    for row in reader: 
     # Look up each value in your dictionary and return the 
     # corresponding 'changes' value if it finds a match. 
     # If a match isn't found, just return the item itself. 
     print [changes.get(item, item) for item in row] 

這將輸出:

['item', 'amount', 'size', 'price'] 
['apple', 12, '3', '8'] 
['cherry', '84', '100 g', '3.5'] 
['orange', 12, '3', '9'] 

print這裏只是爲了顯示輸出 - 你可以調整,以適應無論你的使用情況。

+0

謝謝!我認爲在操作csv文件時答案會起作用。 import csv l = open('amount.csv','rb') 對此變化有何建議? – Sean

+0

@Sean當然,我只是添加了一個編輯 - 讓我知道,如果這有所幫助。 – RocketDonkey

+0

它的確如此,我需要閱讀更多關於列表的信息,遇到列表中的每個字母都是對象的問題:['i','t','e','m',',','a' ''','','','','','','','','','','','',''','' r','i','c','e','\ r','\ n'] ['a','p','p','l','e',',' ,'','','d','o','z','e','n',',','3',',','8','\ r',' \ n'] ['c','h','e','r','r','y',',','8','4',',','1',' '0','0','','g',',','3','。','5'] – Sean

相關問題