用Python替换CSV中的值

0 投票
2 回答
813 浏览
提问于 2025-04-17 20:38

我需要在一个很大的CSV文件中替换一些值,决定使用Python作为编程语言。

我需要更改的值是每行的第一个值,这个CSV文件是用逗号分隔的:

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

这个值总是一个数字,但数字的位数不固定。

目前我有两个想法:逐行处理数据,然后 ...

  1. 使用正则表达式来匹配这个数字
  2. 使用CSV组件来解析这一行

因为我对Python还很陌生,所以有一些问题浮现在我脑海中:

  • 考虑到文件的大小(超过50GB,大约有1000万行),哪种方法更快?
  • 怎么做才能不浪费很多资源?

2 个回答

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个核心,主频为2.4 GHz,内存为8 Gb,得到了以下的处理时间:

$ time python example.py

real    0m20.771s
user    0m20.336s
sys 0m0.369s
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()

撰写回答