我创建了以下代码。这段代码的目的是扫描指定的目录,检查哪些文件以数字结尾,然后执行我之前创建的 python 程序,该程序将对以数字结尾的文件实现更改。
def my_main():
for filenames in os.listdir("dir/"):
if filenames.endswith("1.txt"):
execfile('Location of previous python program')
elif filenames.endswith("2.txt"):
execfile('Location of previous python program')
elif filenames.endswith("3.txt"):
execfile('Location of previous python program')
elif filenames.endswith("4.txt"):
execfile('Location of previous python program')
elif filenames.endswith("5.txt"):
execfile('Location of previous python program')
elif filenames.endswith("6.txt"):
execfile('Location of previous python program')
elif filenames.endswith("7.txt"):
execfile('Location of previous python program')
elif filenames.endswith("8.txt"):
execfile('Location of previous python program')
elif filenames.endswith("9.txt"):
execfile('Location of previous python program')
elif filenames.endswith("10.txt"):
execfile('Location of previous python program')
我正在寻求帮助,以了解如何改进我的代码,我希望它更干净,而不是那么困惑,我也希望它能够通用,而不仅仅是硬连线在某个目录中工作。
任何有关我如何实现这一目标的建议将不胜感激。
谢谢。
最佳答案
您可以使用glob
来查找您感兴趣的文件:
from glob import glob
files = glob("/dir/*[0-9].txt"):
此外,str.endswith
接受一组参数,因此您需要一个 if
而不是 10:
ends = ( "1.txt","2.txt","3.txt"....)
if filenames.endswith(ends):
........
如果您只想查看是否有任何匹配项,请使用 iglob
:
from glob import iglob
if next(iglob("/dir/*[0-9].txt"), None):
............
iglob
返回一个迭代器,因此如果 next(iglob("/dir/*[0-9]*.txt"), None)
不返回默认值无
您知道您至少有一场比赛。
关于python - python 读取以数字结尾的目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34106696/