python - python 读取以数字结尾的目录中的文件

标签 python file directory

我创建了以下代码。这段代码的目的是扫描指定的目录,检查哪些文件以数字结尾,然后执行我之前创建的 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/

相关文章:

c# - 查找文件夹中的所有文件

perl - Perl 中的波浪号 (~) 目录

python - 将函数应用于 faker

python - 按间隔中的位置对组进行计数

c++ - 如何从文本文件中读取并在 C 中拆分句子

c# - 将文件夹移动到 UWP 中另一个位置的最快方法

python - 应用引擎 : What is the lifetime of the app-level registry in webapp2

python - 如何轻松分发具有 Python 模块依赖项的 Python 软件?在 Unix 上安装 Python 包的挫折

file - 根据平台创建动态文件路径

java - 我正在尝试删除空格并将文本文件转换为单行