Python 根据名称模式查找特定文件的代码-break命令有问题
我是python新手,这是我的第一个问题。如果有任何提示,我将不胜感激 我编写了一段代码,它迭代指定文件夹中的文件,以查找名称与正则表达式模式(文件名的一部分)匹配的文件。代码可以正常工作,但我有一个问题。请看一看,然后我会解释:Python 根据名称模式查找特定文件的代码-break命令有问题,python,Python,我是python新手,这是我的第一个问题。如果有任何提示,我将不胜感激 我编写了一段代码,它迭代指定文件夹中的文件,以查找名称与正则表达式模式(文件名的一部分)匹配的文件。代码可以正常工作,但我有一个问题。请看一看,然后我会解释: import re, os, sys basedir = '/home/user_name/python_files' print('Please specify DG, year and dossier number.') print() DG = input(
import re, os, sys
basedir = '/home/user_name/python_files'
print('Please specify DG, year and dossier number.')
print()
DG = input('DG: ')
year = str(input('Year: '))
dossier = str(input('Dossier: '))
fileregex = DG + '-'+ year + '-' + dossier
for r, d, f in os.walk(basedir):
for file in f:
if re.match(fileregex, file, re.I):
print('I found the file', file, 'in', os.path.join(r))
break
else:
print('File not found')
当代码找到文件时,它打印出文件名并中断;如果未找到,则打印出未找到的文件
。到目前为止,一切顺利。但是,代码在找到第一个匹配项后会中断,我希望它继续查找其他匹配项
如果删除break
语句,它会找到其他(部分匹配的)文件,但也会打印出filenotfound
如何确保代码在找到所有匹配项后仅断开,并仅在未找到任何匹配项时打印出未找到文件
谢谢。
Greg可以使用列表存储数据,然后检查列表是否为空
这是我的解决办法
files = []
for r, d, f in os.walk(basedir):
for file in f:
if re.match(fileregex, file, re.I):
files.append([file, os.path.join(r)])
if len(files) > 0:
for file in files:
print(f"I found a file {file[0]} in {file[1]}")
else:
print('File not found')
可以使用列表存储数据,然后检查列表是否为空
这是我的解决办法
files = []
for r, d, f in os.walk(basedir):
for file in f:
if re.match(fileregex, file, re.I):
files.append([file, os.path.join(r)])
if len(files) > 0:
for file in files:
print(f"I found a file {file[0]} in {file[1]}")
else:
print('File not found')
您可以将所有匹配项保存在列表中。如果没有匹配项,则列表的长度为og 0,因此您可以检查列表的长度以查看是否有匹配项
matches = []
for r, d, f in os.walk(basedir):
for file in f:
if re.match(fileregex, file, re.I):
matches.append((file, os.path.join(r)))
if len(matches) == 0:
print('File not found')
else:
for file, path in matches:
print(f'This file was a match: {file} and was found: {path}')
您可以将所有匹配项保存在列表中。如果没有匹配项,则列表的长度为og 0,因此您可以检查列表的长度以查看是否有匹配项
matches = []
for r, d, f in os.walk(basedir):
for file in f:
if re.match(fileregex, file, re.I):
matches.append((file, os.path.join(r)))
if len(matches) == 0:
print('File not found')
else:
for file, path in matches:
print(f'This file was a match: {file} and was found: {path}')
对于else
构造,您不需要。试着用另一种方式来表达你的想法。提示:一种方法是使用标志变量。但看看是否还有另一个更优雅的解决方案:)也许可以考虑使用“While”。例如,将一些代码嵌套在while循环中,如下所示:while allMatchesNotFound==False…do stuff。Else:找到所有匹配项。Else
构造不需要。试着用另一种方式来表达你的想法。提示:一种方法是使用标志变量。但看看是否还有另一个更优雅的解决方案:)也许可以考虑使用“While”。例如,将一些代码嵌套在while循环中,如下所示:while allMatchesNotFound==False…do stuff。Else:找到所有匹配项他想要he目录他也想要he目录