Python을 사용하여 디렉토리에 있는 파일 수를 계산하는 방법

Python을 사용하여 디렉토리에 있는 파일 수를 계산해야 합니다.

가장 쉬운 방법은 len(glob.glob('*'))이지만 디렉토리 자체를 파일로 계산하는 방법도 있습니다.

디렉토리에 있는 _파일_만 계산하는 방법은 없나요?

질문에 대한 의견 (1)
해결책

os.listdir()을 사용하는 것이 glob.glob을 사용하는 것보다 약간 더 효율적입니다. 파일 이름이 디렉토리나 다른 엔티티가 아닌 일반 파일인지 테스트하려면 os.path.isfile()을 사용합니다:

import os, os.path

# simple version for working with CWD
print len([name for name in os.listdir('.') if os.path.isfile(name)])

# path joining version for other paths
DIR = '/tmp'
print len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])
해설 (7)
import os

path, dirs, files = next(os.walk("/usr/lib"))
file_count = len(files)
해설 (3)

모든 종류의 파일, 서브디렉토리가 다음과 같습니다.

import os

list = os.listdir(dir) # dir is your directory path
number_files = len(list)
print number_files

, (방지 서브디렉토리가) :&lt 파일만 br&gt.

import os

onlyfiles = next(os.walk(dir))[2] #dir is your directory path as string
print len(onlyfiles)
해설 (1)

여기서 완료되니라 프 마치 매우 유용합니다.

import fnmatch

print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))

자세한 내용은: http://docs.python.org/2/library/fnmatch.html

해설 (1)
import os
print len(os.listdir(os.getcwd()))
해설 (1)
def directory(path,extension):
  list_dir = []
  list_dir = os.listdir(path)
  count = 0
  for file in list_dir:
    if file.endswith(extension): # eg: '.txt'
      count += 1
  return count
해설 (0)

내가 놀란 것은 없는 '오스릭스칸돈 이어':

def count_files(dir):
    return len([1 for x in list(os.scandir(dir)) if x.is_file()])
해설 (1)

이것은 os.listdir을 사용하며 모든 디렉터리에서 작동합니다:

import os
directory = 'mydirpath'

number_of_files = len([item for item in os.listdir(directory) if os.path.isfile(os.path.join(directory, item))])

생성기를 사용하면 이 과정을 단순화하고 조금 더 빠르게 만들 수 있습니다:

import os
isfile = os.path.isfile
join = os.path.join

directory = 'mydirpath'
number_of_files = sum(1 for item in os.listdir(directory) if isfile(join(directory, item)))
해설 (0)

스케쳐내 수 있는 모든 파일을 파일, 디렉터리 등 서브디렉토리가 가장 파이썬 방법은.

import os

file_count = sum(len(files) for _, _, files in os.walk(r'C:\Dropbox'))
print(file_count)

즉 우리가 사용하는 파일 수를 합한 것보다 더 빠른 속도로 명시적으로 추가 (타이밍 보류)

해설 (2)
def count_em(valid_path):
   x = 0
   for root, dirs, files in os.walk(valid_path):
       for f in files:
            x = x+1
print "There are", x, "files in this directory."
return x

이 게시물]1에서 가져옴

해설 (1)

이것은 단순한 한 줄짜리 명령을 I found 유용합니다.

print int(os.popen("ls | wc -l").read())
해설 (0)
import os

def count_files(in_directory):
    joiner= (in_directory + os.path.sep).__add__
    return sum(
        os.path.isfile(filename)
        for filename
        in map(joiner, os.listdir(in_directory))
    )

>>> count_files("/usr/lib")
1797
>>> len(os.listdir("/usr/lib"))
2049
해설 (0)

39 의 코드를 luke& 재적용됩니다.

import os

print len(os.walk('/usr/lib').next()[2])
해설 (1)

I agree 함께 제공하는 동시에 오토메이티드 @DanielStutzbach: '오스트리스타디르 ()' 을 사용하는 것보다 조금 더 효율적인 '글로브룩스그로브'.

그러나 할 수 없는 경우 추가 precisiontm 사용할 수 있는 특정 파일 폴더 '렌 (글로브룩스그로브 ())'. 예를 들어 만약에 조교하실 사용할 수 있는 모든 pdf 를 폴더란.

pdfCounter = len(glob.glob1(myPath,"*.pdf"))
해설 (0)

import os

total_con=os.listdir('
해설 (1)

39 를 사용할 경우, ll you& 운영 체제의 표준 쉘로 훨씬 빠른 방법을 사용하지 않고 순수 파이썬 결과를 얻을 수 있습니다.

예 windows*용):

import os
import subprocess

def get_num_files(path):
    cmd = 'DIR \"%s\" /A-D /B /S | FIND /C /V ""' % path
    return int(subprocess.check_output(cmd, shell=True))
해설 (1)

내가 다른 답을 찾을 수 있는 기준 수락됨 대답.

for root, dirs, files in os.walk(input_path):    
for name in files:
    if os.path.splitext(name)[1] == '.TXT' or os.path.splitext(name)[1] == '.txt':
        datafiles.append(os.path.join(root,name)) 

print len(files) 
해설 (0)

이 방법은 간단합니다.

print(len([iq for iq in os.scandir('PATH')]))

이는 단순히 번역 기술을 사용한 파일 수를 들려주시겠습니까 디렉터리에서의, 특정 디렉터리 목록을 다시 반복할 수 있는 모든 파일이 귀의하노라 렌 (반환되었습니다 목록) &quot "; 파일 숫자를 되돌려줍니다.

해설 (2)

'나' 를 사용한 글로브룩스그로브 디렉터리입니다 유사한 구조를

data
└───train
│   └───subfolder1
│   |   │   file111.png
│   |   │   file112.png
│   |   │   ...
│   |
│   └───subfolder2
│       │   file121.png
│       │   file122.png
│       │   ...
└───test
    │   file221.png
    │   file222.png

다음과 같은 두 가지 옵션 4 ( 즉 예상대로 반품하십시오. 언약보다는 서브폴더에 요구한 스스로 )

  • '렌 (목록 (글로브룩스그로브 (,, &quot data/train//.png&quot 반복 = True)))'
  • 'sum (1 에서 내가 글로브룩스그로브 (data/train//.png&quot ";))'
해설 (0)

내가 이 수를 반환되었습니다 이런게야 및 폴더 내의 파일을 (Attack_Data) 스티스 작동합니다.

import os
def fcount(path):
    #Counts the number of files in a directory
    count = 0
    for f in os.listdir(path):
        if os.path.isfile(os.path.join(path, f)):
            count += 1

    return count
path = r"C:\Users\EE EKORO\Desktop\Attack_Data" #Read files in folder
print (fcount(path))
해설 (1)