在文件中查找唯一条目

时间:2018-03-11 09:11:23

标签: python python-3.x

猜测你有一个关于以下问题的解决方案:

我想比较常见条目的两个列表(基于第10列),并将公共条目写入一个文件,将第一个列表的唯一条目写入另一个文件。我写的代码是:

INFILE1 = open ("c:\\python\\test\\58962.filtered.csv", "r")
INFILE2 = open ("c:\\python\\test\\83887.filtered.csv", "r")
OUTFILE1 = open ("c:\\python\\test\\58962_vs_83887.common.csv", "w")
OUTFILE2 = open ("c:\\python\\test\\58962_vs_83887.unique.csv", "w")
for line in INFILE1:
    line = line.rstrip().split(",")
    if line[11] in INFILE2:
        OUTFILE1.write(line)
    else:
        OUTFILE2.write(line)    
INFILE1.close()
INFILE2.close()
OUTFILE1.close()
OUTFILE2.close()

出现以下错误:

      8         OUTFILE1.write(line)
      9     else:
---> 10         OUTFILE2.write(line)
     11 INFILE1.close()
TypeError: write() argument must be str, not list

有人知道这方面的帮助吗?

最佳

1 个答案:

答案 0 :(得分:0)

这一行

line = line.rstrip().split(",")

替换您通过文件分割line从文件中读取的list。然后尝试将拆分列表写入您的文件 - 这不是写入方法的工作方式,而是告诉您完全

将其更改为:

for line in INFILE1:
    lineList = line.rstrip().split(",")  # dont overwrite line, use lineList
    if lineList[11] in INFILE2:          # used lineList
        OUTFILE1.write(line)                 # corrected indentation
    else:
        OUTFILE2.write(line) 

您可以自己轻松找到错误,只需在分割之前和之后打印出来,或者只是写作。

请阅读How to debug small programs (#1)并关注它 - 您可以更轻松地自行查找和修复错误,然后在此处发布问题。

你手头还有其他问题:

文件是基于流的,它们以文件中的0位置开头。如果您访问文件的某些部分,则位置会提前。在最后,你不会通过使用INFILE2.read()或其他方法得到任何东西。

因此,如果您想重复检查 file1 的某些行列是否位于 file2 中的某个位置,则需要将 file2 读入列表中(或其他数据结构)所以你的重复检查工作。换句话说,这个:

if lineList[11] in INFILE2: 

可能会工作一次,然后文件被消耗,并且它将一直返回false。

您可能还想更改:

f = open(...., ...)
# do something with f
f.close()

with open(name,"r") as f:
    # do something with f, no close needed, closed when leaving block

因为它更安全,即使发生异常也会关闭文件。

要解决这个问题,请尝试这个(未经测试的)代码:

with open ("c:\\python\\test\\83887.filtered.csv", "r") as file2:
    infile2 = file2.readlines() # read in all lines as list

with open ("c:\\python\\test\\58962.filtered.csv", "r") as INFILE1:
    # next 2 lines are 1 line, \ at end signifies line continues
    with open ("c:\\python\\test\\58962_vs_83887.common.csv", "w") as OUTFILE1, \ 
    with open ("c:\\python\\test\\58962_vs_83887.unique.csv", "w") as OUTFILE2:
        for line in INFILE1:
            lineList = line.rstrip().split(",")
            if any(lineList[11] in x for x in infile2):  # check the list of lines if 
                                                     # any contains line[11]
                OUTFILE1.write(line)
            else:
                OUTFILE2.write(line)    
    # all files are autoclosed here

链接阅读:

相关问题