通过Python中的列表元素过滤csv内容

问题描述:

我陷入了从一段简单的Python代码中获得正确结果(我是一名Python初学者)。 给定一个CSV输入文件(ListInput.csv): PKT,PET,PUT,通过Python中的列表元素过滤csv内容

和其中包含许多这些元素(Table.csv)的特征的另一csv文件:

pBR,156,AATGGT,673,HHHTTTT, 
pUT,54,CCATGTACCTAT,187,PRPTP, 
pHTM,164,GGTATAG,971,WYT, 
pKT,12,GCATACAGGAC,349,, 
pET,87,GTGACGGTA,506,PPMK, 

.. ..........等等

我的目标是获得一个基于第一个csv文件元素的选择,以获得一个csv文件作为输出(WorkingList.txt),在这种情况下预期结果将是:

pKT,12,GCATACAGGAC,349,, 
pET,87,GTGACGGTA,506,PPMK, 
pUT,54,CCATGTACCTAT,187,PRPTP, 

我写了下面的脚本,它不会给出错误,但最终会有一个空文件作为输出。我尝试了解为什么因为几天没有成功。任何帮助都不胜感激。

#!/usr/bin/python 
import csv 

v = open('ListInput.csv', 'rt') 
csv_v = csv.reader(v) 

vt = open('Table.csv', 'rt') 
csv_vt = csv.reader(vt) 

with open("WorkingList.txt", "a+t") as myfile: 
    pass 


for el in csv_v: 
    for var in csv_vt: 
     if el == var[0]: 
      myfile.write(var) 

myfile.close() 

第一个问题:

您在第一次迭代消耗你输入CSV迭代csv_vt。您需要执行以下操作:

vt.seek(0) 

将文件倒回到内循环中。这留下一个O(n^2)搜索算法,但至少它工作。

问题二:

你在with块打开&收盘my_file。当你到达for循环时,my_file已经关闭,因为你离开了with区块(这是with区块的保证)。

当你试图编写输出时,你有没有第一个问题,你有“关闭文件操作”的路径。

我会重写with块内的最后一部分并删除close()

第三个问题

你不能写一个清单文件,你必须首先创建一个csv.writer对象。

所以总结起来,可以解决所有的问题,加上性能问题与下面的代码:

#!/usr/bin/python 
import csv 

v = open('ListInput.csv', 'rt') 
csv_v = csv.reader(v) 

with open('Table.csv', 'rt') as vt: 
    csv_vt = csv.reader(vt) 
    # create a dictionary to speed up lookup 
    # read the table only once 
    vdict = {var[0]:var for var in csv_vt} 

with open("WorkingList.txt", newline="") as myfile: # for Python 3.x 
## with open("WorkingList.txt", "wb") as myfile: # for Python 2 
    cw = csv.writer(myfile) 
    for el in csv_v: 
     if el[0] in vdict: 
      cw.writerow(vdict[el]) 

v.close() 

vdict是查找表将取代你的内环(只能当“钥匙”是独特的,这似乎是给你的输入样本)

+0

对!因为我在最终的代码中复制了你的错误。看看我的编辑'如果vdict中的el [0]:'检查第一列是否在字典中(不像以前那样是整行) –

+0

您的非工作代码的另一个剩余部分已修复。你必须使用csv.writer。 –

+0

对不起。编码没有测试是罪魁祸首。你需要'writerow'。 –

解决!这里是一段代码的作品:

import csv 

with open('ListInput.csv', 'rt') as csvfile: 
    readCSV = csv.reader(csvfile, delimiter=',') 
    vinput = [] 
    flist = [] 
    for row in readCSV: 
     vi = row 
     vinput.append(vi) 

     print(vinput) 

with open('Table.csv', 'rt') as csvfile: 
    readTable = csv.reader(csvfile, delimiter=',') 
    vtable = [] 
    for row in readTable: 
     vt = row 
     for rig in vi: 
      el = rig 
      if str(el) in vt: 
       vtable.append(vt) 


    print(vtable)   

with open (r'WorkingTable.csv', 'w', newline='') as write_file: 
    write=csv.writer(write_file) 
    write.writerows([r] for r in vtable)