【问题标题】:how to find and replace in csv using python如何使用python在csv中查找和替换
【发布时间】:2018-01-14 20:51:07
【问题描述】:

我有 900 行和 11 列的 csv 文件。它包含大约 4000 个链接,我想用 4000 个链接替换它们(我有另一个 csv 文件,其中包含第 1 列和第 2 列中的链接)。 我正在尝试使用 python 自动化它(查找和替换) 这是我的代码,但它不起作用。实际上我没有收到任何错误,但程序连续运行而没有给出任何结果。我运行了 2. 3 个小时,然后无助地杀死了它。

import csv 
def replace_all(text, dic):
  for i, j in dic.iteritems():
   text = text.replace(i, j)
 return text

with open('file_that_find_replace_data.csv', mode='r') as infile:
 reader = csv.reader(infile)
 d = {rows[0]:rows[1] for rows in reader}

f = open('main_file.csv','r') 
filedata = f.read() 
for row in filedata:
  newdata = replace_all(filedata, d)

f = open('main_file.csv','w') 
f.write(newdata) 
f.close()
print ('done')

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建minimal reproducible example
  • (我没有投反对票,但这就是你被投反对票的原因)
  • 你为什么不用csv模块来阅读main.csv
  • “它不工作”可能是一个准确的描述,但我们需要更多信息。
  • 对,但您仍然可以调试。添加一些 print() 函数。 d 是否包含您的期望?每个循环内的打印会告诉你它卡在哪里。新数据也一样。或者在交互式 python shell 或 IPython 中逐节粘贴它。

标签: python csv file-read


【解决方案1】:
for row in filedata:
  newdata = replace_all(filedata, d)

这将只留下newdata 中文件的最后一行。也许是newdata +=?或者在循环中写入输出行。而且,为什么不对这两个文件都使用 csvfile 呢?

【讨论】:

    【解决方案2】:

    我自己解决了 谢谢大家的帮助

    import csv
    findd=[]
    repl=[]
    with open('find_replace_data.csv', mode='r') as infile:
      reader = csv.reader(infile)
      for rows in reader:
          a= rows[0]
          b= rows[1]
          findd.append(a)
          repl.append(b)
    
    
    
    ifile = open('infile.csv', 'rb')
    reader = csv.reader(ifile)
    ofile = open('outfile.csv', 'wb')
    writer = csv.writer(ofile)
    
    rep = dict(zip(findd, repl))
    
    s = ifile.read()
    for item in findd:
        s = s.replace(item, rep[item])
    ofile.write(s)
    ifile.close()
    ofile.close() 
    

    【讨论】:

      猜你喜欢
      • 2011-04-25
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 2021-10-09
      • 2011-09-25
      • 2014-04-08
      相关资源
      最近更新 更多