【问题标题】:Finding files in directories in Python在 Python 中查找目录中的文件
【发布时间】:2015-05-22 03:46:22
【问题描述】:

我一直在编写一些脚本,我需要访问操作系统来命名图像(单击时保存 Mandelbrot 集的每个后续缩放),方法是计算目录中的所有当前文件,然后使用 %s 来命名它们在调用以下函数后在字符串中添加一个选项以将它们全部删除

我意识到下面将始终获取文件的绝对路径,但假设我们始终在同一个目录中,是否没有简化版本来获取当前工作目录

def count_files(self):
     count = 0
     for files in os.listdir(os.path.abspath(__file__))):
         if files.endswith(someext):
             count += 1
     return count

def delete_files(self):
     for files in os.listdir(os.path.abspath(__file__))):
         if files.endswith(.someext):
             os.remove(files)

【问题讨论】:

    标签: python python-3.x data-structures operating-system filesystems


    【解决方案1】:

    由于您正在做 .endswith 的事情,我认为 glob 模块可能会引起一些兴趣。

    以下打印当前工作目录中扩展名为 .py 的所有文件。不仅如此,它只返回文件名,而不是路径,正如你所说的那样:

    import glob
    
    for fn in glob.glob('*.py'): print(fn)
    

    输出:

    temp1.py temp2.​​py temp3.py _clean.py

    编辑:重新阅读您的问题,我不确定您真正在问什么。如果您想要一种更简单的方法来获取当前工作目录而不是

    os.path.abspath(__file__) 
    

    那么是的,os.getcwd()

    但是,如果您更改脚本中的工作目录(例如通过os.chdir()),os.getcwd() 将会更改,而您的方法不会。

    【讨论】:

    • 是的,这就是我要找的东西,如果不清楚的话,抱歉。
    【解决方案2】:

    使用antipathy* 会更容易一些:

    from antipathy import Path
    
    def count_files(pattern):
        return len(Path(__file__).glob(pattern))
    
    def deletet_files(pattern):
        Path(__file__).unlink(pattern)
    

    *披露:我是反感的作者。

    【讨论】:

      【解决方案3】:

      您可以使用os.path.dirname(path) 获取path 指向的事物的父目录。

      def count_files(self):
       count = 0
       for files in os.listdir(os.path.dirname(os.path.abspath(__file__)))):
           if files.endswith(someext):
               count += 1
       return count
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多