替换csv python模块中的多个单元格

时间:2016-02-15 10:40:46

标签: python python-2.7 python-3.x

我有一个大的csv文件(逗号分隔)。我想用值“NIL”替换/重命名几个随机单元格为空字符串“”。

我试图找到关键字"NIL"并将''替换为空 串。但它给了我一个空的csv文件

ifile = open('outfile', 'rb') 
reader = csv.reader(ifile,delimiter='\t') 
ofile = open('pp', 'wb') 
writer = csv.writer(ofile, delimiter='\t') 
findlist = ['NIL'] 
replacelist = [' '] 
s = ifile.read() 
for item, replacement in zip(findlist, replacelist): 
    s = s.replace(item, replacement) 
ofile.write(s)

2 个答案:

答案 0 :(得分:0)

从看到你的代码我直接摔倒了

阅读文件

with open("test.csv") as opened_file:
    data = opened_file.read()

然后使用正则表达式将所有NIL更改为“”或“”并将数据保存回文件。

import re

data = re.sub("NIL"," ",data) # this code will replace NIL with " " in the data string

注意:您可以提供任何正则表达式而不是NIL

有关详细信息,请参阅re模块。

编辑1:re.sub返回一个新字符串,因此您需要将其返回data

答案 1 :(得分:0)

一些调整和你的例子有效。我编辑了你的问题以摆脱一些缩进错误 - 假设那些是剪切/粘贴问题。接下来的问题是你没有import csv ......但即使你创建了一个读者和作家,你实际上并没有使用它们,所以它可以被删除。因此,以文本而不是二进制模式打开,我们有

ifile = open('outfile')  # 'outfile' is the input file... 
ofile = open('pp', 'w') 
findlist = ['NIL'] 
replacelist = [' '] 
s = ifile.read() 
for item, replacement in zip(findlist, replacelist): 
    s = s.replace(item, replacement) 
ofile.write(s)

我们可以添加'条款并使用dict使替换更清晰

replace_this = { 'NIL': ' '}
with open('outfile') as ifile, open('pp', 'w') as ofile: 
    s = ifile.read() 
for item, replacement in replace_this.items: 
    s = s.replace(item, replacement) 
ofile.write(s)

现在唯一真正的问题是它也会改变像#&n; NILIST"到" IST"。如果这是一个除了" NIL"之外的所有数字的csv,那不是问题。但是你也可以使用csv模块来只改变那些完全" NIL"

的单元格。
with open('outfile') as ifile, open('pp', 'w') as ofile:
    reader = csv.reader(ifile)
    writer = csv.writer(ofile)
    for row in reader:
        # row is a list of columns. The following builds a new list
        # while checking and changing any column that is 'NIL'. 
        writer.writerow([c if c.strip() != 'NIL' else ' ' 
            for c in row])
相关问题