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

替换csv python模块中的多个单元格,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我有一个大的csv文件(逗号分隔)。我想将值为“NIL”的少数随机单元格替换/重命名为空字符串“” 我试图找到关键字“NIL”,并替换为“空 一串但它给了我一个空的csv文件 ifile=open('outfile','rb') reader=csv.reader(ifile,分隔符='\t') ofile=open('pp','wb') writer=csv.writer(文件,分隔符='\t') findlist=['NIL'] 替换列表=[“”] s=ifile.read() 对于项目,在

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

我试图找到关键字
“NIL”
,并替换为
空 一串但它给了我一个空的csv文件

ifile=open('outfile','rb')
reader=csv.reader(ifile,分隔符='\t')
ofile=open('pp','wb')
writer=csv.writer(文件,分隔符='\t')
findlist=['NIL']
替换列表=[“”]
s=ifile.read()
对于项目,在zip中替换(findlist,replacelist):
s=s.更换(项目,更换)
ofile.write(s)

看到你编写代码,我觉得你应该

读文件

with open("test.csv") as opened_file:
    data = opened_file.read()
然后使用regex将所有NIL更改为“”或“”,并将数据保存回文件

import re

data = re.sub("NIL"," ",data) # this code will replace NIL with " " in the data string
注意:您可以给出任何正则表达式,而不是
NIL

有关更多信息,请参阅模块


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

进行一些调整,这样您的示例就可以运行了。我编辑了你的问题以消除一些缩进错误——假设这些是剪切/粘贴问题。下一个问题是您不导入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)
我们可以添加“with”子句,并使用
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)
现在唯一真正的问题是,它还将“NILIST”之类的东西改为“IST”。如果这是一个csv,包含除“NIL”之外的所有数字,这不是问题。但您也可以使用csv模块仅更改精确为“NIL”的单元格


那么是什么阻止了你呢?我刚开始学习python。所以我不知道python库。我正试图用这个浏览整个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()对于项,zip中的替换(findlist,replacelist):s=s.replace(项,替换)ofile.write(s)`请参见下面的代码。我这样做是为了找到确切的关键字。在我以前的操作中,我还尝试使用2D数组遍历所有单元格,就像我们在C中使用的那样。我可以读取文件,但遗憾的是,无法用匹配的关键字替换文件@EDChumt显示的代码失败,因为它没有导入csv。如果添加了,它将写入文件。当你说,文件没有被写入。。。是因为程序崩溃了,你得到了堆栈跟踪吗?你能说得更具体些吗?我真的是个新手。我正试图自己解决这个问题。我没有任何导师可以帮忙。如果你能给我提供准确的解决方案@我仍然不工作。我试过了,但输出文件和以前一样。@GIRISH RAMNANI
re.sub
不做数据的就地更改,它会返回一个新实例,因此您必须执行类似于
new\u data=re.sub(“NIL”,“data”)的操作。
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])