【问题标题】:python count number of text file in certain directorypython计算某个目录中文本文件的数量
【发布时间】:2018-06-08 03:18:32
【问题描述】:

我正在尝试获取某个目录中的文件数,但我希望它只计算文本文件,因为我在帐户和 DS 中有另一个目录。存储文件。我应该修改什么以仅获取文本文件的数量?

list = os.listdir("data/accounts/")
number_files = len(list)
print(number_files)

【问题讨论】:

    标签: python


    【解决方案1】:

    来自Count number of files with certain extension in Python

    解决方案 1。

    fileCounter = 0
    for root, dirs, files in os.walk("data/accounts/"):
        for file in files:    
            if file.endswith('.txt'):
                fileCounter += 1
    

    解决方案 2。

    fileCounter = len(glob.glob1("data/accounts/","*.txt"))
    

    在此处阅读 glob here

    【讨论】:

    • 这不是两个独立的解决方案吗?
    【解决方案2】:

    可能对您有用的替代模块是glob

    它将允许您使用通配符,这样您就可以只捕获您感兴趣的文件。

    from glob import glob
    filenames = glob("data/accounts/*.txt")
    number_of_files = len(filenames)
    print(number_of_files)
    

    【讨论】:

      【解决方案3】:

      假设您的文本文件以“.txt”结尾,您可以使用以下内容:

      files = [x for x in os.listdir("data/accounts/") if (os.isfile(x) and x.endswith('.txt'))]
      number_files = len(list)
      print(number_files)
      

      使用os.isfile() 忽略目录并使用string.endswith() 确定文本文件。

      【讨论】:

        【解决方案4】:
        number_of_files = sum(f.endswith('.txt') for f in os.listdir("data/accounts/"))
        

        str.endswith() 返回 TrueFalse
        TrueFalse 的数值分别为 1 和 0。
        sum() 将使用生成器表达式。

        【讨论】:

          猜你喜欢
          • 2021-03-05
          • 2020-10-07
          • 2021-09-09
          • 1970-01-01
          • 1970-01-01
          • 2017-07-05
          • 1970-01-01
          • 2011-02-07
          • 2019-01-16
          相关资源
          最近更新 更多