Python 3.x 修改python脚本以在文件中的行中搜索数字范围
我正在尝试编写代码来搜索目录中的文件,如果第五行包含字符串“51”到“100”,它将打印文件名 我已尝试将“for”循环中的第一条语句修改为:Python 3.x 修改python脚本以在文件中的行中搜索数字范围,python-3.x,string,loops,pycharm,Python 3.x,String,Loops,Pycharm,我正在尝试编写代码来搜索目录中的文件,如果第五行包含字符串“51”到“100”,它将打印文件名 我已尝试将“for”循环中的第一条语句修改为: s = i for i in range(51,100): 但这只会返回一个错误,它是在寻找字符串,而不是int path = './data/' files = [f for f in glob.glob(path + "*.crs", recursive=False)] # Open the file for f in files: li
s = i
for i in range(51,100):
但这只会返回一个错误,它是在寻找字符串,而不是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
也许有一种更优雅的方法可以做到这一点,但这就是我想到的。基本上,对于每个文件,它打开文件并逐行读取,直到到达要检查的行。请注意,第5行是文件的第6行,因为行号是从0开始的偏移量。然后它在
numbersToCheck
中检查行中是否有任何数字。我在第二行使用了范围(51100)中的v的str(v)
将整数转换成字符串,然后存储在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()
1.文件支持上下文管理,请使用
和
来打开/关闭它们。2.文件支持迭代协议,如您所示。然后只需跳过第一行,只需一个开始,不需要枚举。3可能使用正则表达式来匹配字符串,或者与OP再次检查文件中的一行包含的内容exactly@Pynchia这些听起来像是很好的编辑。我不太清楚你的第二点是什么意思(这可能是我知识的一个限度)。你会怎么做如果代表允许,请随时编辑答案。调查itertools.islice
或只需对范围内(lineToCheck-1)进行:下一步(fh)
,然后阅读所需行。顺便说一句,enumerate默认从零开始计数,因此您的代码是错误的请显示文件内容的前5或6行它看起来像我刚刚编辑的文章的结尾。不过,我只需将lineToCheck更改为“4”,就得到了它。非常感谢你的帮助!
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()