通过 Python 编程计算文件夹中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27694713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:08:19  来源:igfitidea点击:

Count files in Folder by Python Programming

pythonfilecountnumbersdirectory

提问by Fahadkalis

I am trying to count number of files in my folder (/Home/python) for that reason I make a short program

我正在尝试计算文件夹 (/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))])

but it is given me an error like that

但它给了我这样的错误

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'

Guys can you plz help me to make it bug free program. Thank You

伙计们,你能帮助我让它成为无错误程序。谢谢你

enter image description here

enter image description here

采纳答案by Digisec

Try this instead

试试这个

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))])

This is because you are not in /home/python. You are actually in your home directory which is /home/$USER/python. If you do the following, in a terminal, you will see where you are.

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

cd ~/python && pwd

回答by Jacobr365

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

Just stick the source for that into whatever directory you are counting files in. This only counts files not folders.

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

回答by Padraic Cunningham

It needs to be a lowercase hfor ubuntu homeand you also need to supply your username, so either use path = "/home/user_name/python"or os.path.expanduser.

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

os.path.expanduserwill return something like /home/username/python:

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))])

回答by julio

I think this is the easiest way:

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

import os

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

print(len(dirListing))