代码之家  ›  专栏  ›  技术社区  ›  Ratha

如何计算特定目录中的文件数,而不扫描python中的子文件夹

  •  0
  • Ratha  · 技术社区  · 6 年前

    我试着喜欢;

     files = os.listdir(file_path)
        print(len(files)) <--gets counts of all files in subdirctory too
     for f in files:
      if (f.endswith('.xlsx')):
        print(count of *.clxs files)
    

    我只需要在根目录中计算excel文件,在python中如何计算?

    3 回复  |  直到 6 年前
        1
  •  1
  •   codebee    6 年前

    你可以这么做

    xslx_files=[]
    files = os.listdir(file_path)
        print(len(files)) <--gets counts of all files in subdirctory too
     for f in files:
      if (f.endswith('.xlsx')):
        xslx_files.append(f)
    print(len(xslx_files))
    
        2
  •  1
  •   Iain Shelvington    6 年前

    如果您使用的是python>=3.4版本,则可以使用 pathlib

    base_path = pathlib.Path(file_path)
    num_spreadsheets = len(list(base_path.glob('*.xlsx')))
    
        3
  •  0
  •   mindless-overflow    6 年前
    import os
    for file in os.listdir("/mydir"):
        if file.endswith(".xlsx"):
            print(os.path.join("/mydir", file))