使用python更改csv中的单元格

时间:2013-01-13 22:32:10

标签: python csv cell

如何使用Python 2.7更改某个单元格中的值?创建数据库是最好的方法吗? (改为'1打'到12两次 - 每次'1打'被发现它被替换为12)

输入:

['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']

1 个答案:

答案 0 :(得分: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这里只是为了显示输出 - 您可以调整以适应您的用例。