Python을 사용하여 디렉토리에 있는 파일 수를 계산해야 합니다.
가장 쉬운 방법은 len(glob.glob('*'))
이지만 디렉토리 자체를 파일로 계산하는 방법도 있습니다.
디렉토리에 있는 _파일_만 계산하는 방법은 없나요?
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))])
모든 종류의 파일, 서브디렉토리가 다음과 같습니다.
import os
list = os.listdir(dir) # dir is your directory path
number_files = len(list)
print number_files
, (방지 서브디렉토리가) :< 파일만 br>.
import os
onlyfiles = next(os.walk(dir))[2] #dir is your directory path as string
print len(onlyfiles)
여기서 완료되니라 프 마치 매우 유용합니다.
import fnmatch
print len(fnmatch.filter(os.listdir(dirpath), '*.txt'))
이것은 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)))
스케쳐내 수 있는 모든 파일을 파일, 디렉터리 등 서브디렉토리가 가장 파이썬 방법은.
import os
file_count = sum(len(files) for _, _, files in os.walk(r'C:\Dropbox'))
print(file_count)
즉 우리가 사용하는 파일 수를 합한 것보다 더 빠른 속도로 명시적으로 추가 (타이밍 보류)
import os
total_con=os.listdir('<directory path>')
files=[]
for f_n in total_con:
if os.path.isfile(f_n):
files.append(f_n)
print len(files)
'나' 를 사용한 글로브룩스그로브 디렉터리입니다 유사한 구조를
data
└───train
│ └───subfolder1
│ | │ file111.png
│ | │ file112.png
│ | │ ...
│ |
│ └───subfolder2
│ │ file121.png
│ │ file122.png
│ │ ...
└───test
│ file221.png
│ file222.png
다음과 같은 두 가지 옵션 4 ( 즉 예상대로 반품하십시오. 언약보다는 서브폴더에 요구한 스스로 )
내가 이 수를 반환되었습니다 이런게야 및 폴더 내의 파일을 (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))