修改python脚本以在文件中的一行中搜索数字范围

问题描述 投票:0回答:1

[我正在尝试编写代码来搜索目录中的文件,并且对于第五行中包含字符串“ 51”至“ 100”的任何文件,它将打印文件名。

我已经尝试将'for'循环中的第一条语句修改为:

s = i
for i in range(51,100):

但是这只是返回错误bc,它正在寻找字符串,而不是int

path = './data/'
files = [f for f in glob.glob(path + "*.crs", recursive=False)]

# Open the file
for f in files:
    line = 5
    fh: TextIO = open(f)
    text = fh.read()

    # Conditions
    for line in f:
        s: str = '62'  # Takes input of a string from user

        if s in text:  # string is present in the text file
            print(f)
        break
    else:
        continue
    fh.close()

TypeError: 'in <string>' requires string as left operand, not int

我当前的代码将在第五行中打印出包含'62'的文件的名称。我只是在寻找一种方法,使它在第五行上打印出所有包含51-100之间任何数字的文件。

python-3.x string loops pycharm
1个回答
0
投票

可能有一种更优雅的方法可以做到这一点,但这就是我很快想到的。基本上,对于每个文件,它都会打开文件并逐行读取,直到到达要检查的行为止(请注意,第5行是文件的第六行,因为行号从0开始偏移)。然后,它检查该行中是否有numbersToCheck中的任何数字。我在第二行使用str()将范围内的整数转换为存储在numbersToCheck中的字符串。

lineToCheck = 5
numbersToCheck = [str(v) for v in range(51, 100)] #convert integers to strings

path = './data/'
files = [f for f in glob.glob(path + "*.crs", recursive=False)]

for f in files:
    fh = open(f) #open the file
    for lineNo, line in enumerate(fh):
        if lineNo == lineToCheck: #Once it gets to the correct line
            if any(numberStr in line for numberStr in numbersToCheck): #Checks for numbers
                print(line)
                break #don'1t continue checking this file, move on to the next.
    fh.close()
© www.soinside.com 2019 - 2024. All rights reserved.