【问题标题】:Count files in Folder by Python Programming通过 Python 编程计算文件夹中的文件
【发布时间】:2014-12-29 19:20:57
【问题描述】:

我正在尝试计算我的文件夹中的文件数 (/Home/python) 为此我做了一个小程序

import os.path
path = '/Home/python'
num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])

但它给了我这样的错误

Traceback (most recent call last):
  File "count_number_of_files_folder.py", line 3, in <module>
    num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])
OSError: [Errno 2] No such file or directory: '/Home/python'

伙计们,你能帮我制作一个没有错误的程序吗? 谢谢你

【问题讨论】:

  • 我认为它是绝对路径,但确切地说我不知道​​绝对路径的定义,但你可以在我的问题中查看 /Home/python .. 我刚刚添加了该图像
  • home小写h
  • H 在大写 ome 中是小写
  • @PadraicCunningham:其实是 /home/username/python
  • @PadraicCunningham 我也尝试使用用户名,但仍然相同的错误 Traceback(最近一次调用最后一次):文件“count_number_of_files_folder2.py”,第 4 行,在 num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))]) OSError: [Errno 2] No such file or directory: '/Home/tansen/python'

标签: python file count numbers directory


【解决方案1】:

试试这个

import os.path
path = os.getenv('HOME') + '/python'
num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])

这是因为你不在 /home/python 中。您实际上在您的主目录中,即 /home/$USER/python。如果您执行以下操作,在终端中,您将看到您所在的位置。

cd ~/python && pwd

【讨论】:

  • 现在它给出了那个错误 Traceback (最近一次调用最后一次): File "count_number_of_files_folder.py", line 2, in path = os.env('HOME') + 'python' AttributeError:“模块”对象没有属性“env”
  • 我的错,它是 os.getenv()。这是一个错字。谢谢指正。
  • 是的,你的新代码现在运行良好......即使我不需要直接更改......谢谢
  • 很高兴为您服务 :)
【解决方案2】:

我认为这是最简单的方法:

import os

img_folder_path = 'C:/FolderName/FolderName2/IMG/'
dirListing = os.listdir(img_folder_path)

print(len(dirListing))

【讨论】:

    【解决方案3】:

    对于 ubuntu home,它必须是小写的 h,并且您还需要提供您的用户名,因此请使用 path = "/home/user_name/python"os.path.expanduser

    os.path.expanduser 会返回类似/home/username/python:

    import os
    path = os.path.expanduser("~/python")
    num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])
    

    【讨论】:

      【解决方案4】:
      import glob, os
      file_count = 0
      WorkingPath = os.path.dirname(os.path.abspath(__file__))
      for file in glob.glob(os.path.join(WorkingPath, '*.*')):
          file_count += 1
      

      只需将源代码粘贴到您计算文件所在的任何目录中即可。这只计算文件而不是文件夹。

      【讨论】:

      • 我应该在哪里写我的目标路径?
      • 如果程序本身在目录中,这不会算一个太多文件吗?
      • 从 -1 开始计数,或者只是将 WorkingPath 替换为您想要的任何目录的路径,然后从您想要的任何地方运行它。这是我能想到的最快的方法。
      • 我的工作路径是 '/Home/python' 但它没有给我正确的答案你能不能把这条路径放在程序的正确位置以获得正确的答案
      • @Fahad /Home/python 不是正确的道路。重读帕德莱克的answer
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      相关资源
      最近更新 更多