用Python替换CSV中的值

时间:2014-03-03 16:18:46

标签: python regex csv

我必须替换大型CSV文件中的值,并决定使用Python作为我想要使用的编程语言。

我需要更改的值是逗号分隔CSV中每行的第一个值:

ToReplace, a1, a2, ..., aN
1, ab, cd, ..., xy
80, ka, kl, ..., df

它始终是一个数字,但如果数字不固定则为数量。

我现在有两个想法:逐行处理数据......

  1. 使用正则表达式匹配数字
  2. 使用CSV组件解析行
  3. 由于我对Python很陌生,因此我想到了一些问题:

    • 考虑文件的大小(> 50GB;〜1000万行),哪种方法更快?
    • 如何在不浪费大量资源的情况下实施它?

2 个答案:

答案 0 :(得分:2)

如果要替换始终包含数字的第一列,则可以使用字符串方法而不是更通用的csv模块,以避免解析整行:

#!/usr/bin/env python

def main():
    with open('50gb_file', 'rb') as file, open('output', 'wb') as output_file:
        for line in file:
            number, sep, rest = line.partition(b',')
            try:
                number = int(number)*2 #XXX replace number here
            except ValueError:
                pass # don't replace the number
            else:
                line = bytes(number) + sep + rest
            output_file.write(line)

main()

答案 1 :(得分:0)

你可以将第二个参数传递给Python的split方法,以获得第一个匹配,用你想要的任何东西替换它,然后再加入一个字符串,如下所示:

import logging

with open('example.csv', 'rb') as infile, \
        open('result.csv', 'wb') as outfile:
    for line in in file:
        try:
            number, rest = line.split(',', 1)
            number = 'blob'
            outfile.write(','.join([number, rest]))
        except ValueError:
            logging.error('The following line had no separator: %s', line)

对于1000万行,在2.4 GHz的2个内核和8 Gb RAM上,我得到以下时间:

$ time python example.py

real    0m20.771s
user    0m20.336s
sys 0m0.369s