匹配索引值

时间:2012-07-09 17:12:06

标签: python list indexing matching

这是我目前的代码。我想检查两个值(行)以检查文件中的匹配项。

def checkOS():
    fid1 = open("C:/Python/NSRLOS.txt", 'r')
    fid2 = open("C:/Python/sha_sub_hashes.out", 'r')
    outdata = open("osMatches.txt", 'w')
    line1 = fid1.readline()
    line2 = fid2.readline()
    while(line1 and line2):
        xline= line1.split(',')[1]
        yline = line2.split("|")[3]
        zline = xline.replace('"','')
        if (yline == zline):
            outdata.append([yline , zline])
            print xline, zline

if __name__=="__main__":
    checkOS()

唯一的问题是我不确定我写的是什么,if语句之前的所有代码只是重新格式化以便能够从行的索引中提取。我想知道的是,如果我使用的声明在这个意义上起作用并且它是否有效?然后我想输出相等的值。 以下是文件中的一些行:

file2:
"10","Amstrad 6128","Unknown","1006"
"100","Macintosh 9.0","8.5.1","67"
"101","Macintosh 9.0.4","na","67"
"102","Macintosh 9.1","9.1","67"
"103","Macintosh 9.2","9.2","67"
"104","Macintosh 9.2.2","9.2.2","67"
"105","Macintosh 9.x","9.X","67"
"106","Macintosh X","10","67"
"107","Macintosh7.5.3","7.5.3","67"
"108","NetWare","n/a","674"
"109","Novel Dos 7.0","7","609"
"11","Apple II+","Unknown","67"
"110","OS/2","Unknown","427"



file2:

    DD84270022E57F1850C8454FA432ADFF99588157B|index.docbook|2225|Redhat 7.3 (32bit)|Linux

D84270022E57F1850C8464F5432ADFF99588157B|index.docbook|2225|Redhat 8.0 (32bit)|Linux

26EEEB25D7005F9FF9EE05A8084C77242702FBAD|Localizable.strings|2142|Mac OS X 10.4|OSX

34DC3D728C34E32F090307F575254D57E53C53FF|SYSTEM|10747904|Windows 7 Home Premium (32bit)|Windows

279E5A766C88EEA5AB946A0AF8D0C4FC366B2AF9|totem.devhelp|21324|Linux Ubuntu Desktop 9.10 (32bit)|Linux

279E5A766C88EEA5AB964A0AF8D0C4FC366B2AF9|totem.devhelp|21324|Linux Ubuntu Desktop 9.10 (64bit)|Linux

B3D11390AB8683BBE443A415EDD91BFDFD482134|dslconfig.pyc|6246|Redhat 9.0 (32bit)|Linux

现在你可能在这几行中找不到任何即时匹配,但是我知道在某个地方会有至少一个匹配,因为我在浏览文件时看到了。

1 个答案:

答案 0 :(得分:1)

你可能正在寻找这样的东西:

使用with()它会自动为您关闭文件。

def checkOS():
    with open("C:/Python/NSRLOS.txt") as fid1,open("C:/Python/sha_sub_hashes.out") as fid2,open("osMatches.txt", 'w') as outdata:
        for xline,yline in zip(fid1,fid2):  #zip fetches lines from both files one by one                                           
            xline= xline.split(',')[1]      #use itertools.izip instead of zip if you're on python 2.x
            yline = yline.split("|")[3]
            zline = xline.replace('"','')
            if yline == zline:                
                outdata.write("{0}{1}\n".format(yline , zline)) #use write to write the data back

if __name__=="__main__":
checkOS()