使用python搜索文件中的字符串

时间:2019-04-18 18:36:28

标签: python-2.7

我几乎需要做'grep -i str file'所给予的回报,但是多年来我一直在努力解决这个问题。

我有一个名为'siteLookup'的函数,该函数传递两个参数:str's'和file_handle'f'。 我想a)确定是否存在(单个)字符串(在此示例中为site="XX001"), b)如果找到了,请在其中找到行,然后将我从该[found]行中提取的另一个字段值返回给调用方。 (这是“ csv”查询)。我已经定期进行此操作,但是随后它将停止工作,我不明白为什么。

我尝试了所有不同的“打开”选项,包括f.readlines等。

#example line: 'XX001,-1,10.1.1.1/30,By+Location/CC/City Name/'
#example from lookupFile.csv: "XX001","Charleston","United States"

sf = open('lookupFile.csv')

def siteLookup(s, f):
    site = s.split(',')[0].strip().upper()
    if len(site) == 5:
        f.seek(0)
        for line in f:
            if line.find(site)>=0:
                city = line.split(',')[1].strip('"').upper()
                return city
            # else site not found 
            return -1
    else:  # len(site) != 5
        return -1

city = siteLookup(line, sf)
print(city)
sf.close()

此代码中的匹配项为零。 (我已将此示例代码简化为单个搜索)。我希望获得与5位数站点代码匹配的城市的名称-站点代码是示例“行”中的第一个字段。

任何帮助非常感谢

1 个答案:

答案 0 :(得分:1)

您的return的缩进错误-如果在第一行中找不到您要查找的内容,它将返回-1,并且不会进一步查找。

使用with open(...) as f:来提高代码的安全性:

以open(“ lookupFile.csv”,“ w”)作为f:     f.write(“”“#lookupFile.csv中的示例: “ XX001”,“查尔斯顿”,“美国” “””)

def siteLookup(s, f):
    site = s.split(',')[0].strip().upper()
    if len(site) == 5:
        f.seek(0)
        for line in f:
            if site in line:   # if site in line is easier for checking 
                city = line.split(',')[1].strip('"').upper()
                return city

        # wrongly indented - will return if site not in line
        # return -1

    # if too short or not found, return -1 - no need for 2 returns  
    return -1


line = 'XX001,-1,10.1.1.1/30,By+Location/CC/City Name/'

with open('lookupFile.csv') as sf:
    city = siteLookup(line, sf)
    print(city)

输出:

CHARLESTON