나는 os.walk (), glob 또는 fnmatch를 사용하지 않는이 프로그램을 작성했으며 이는 의도적 인 것입니다. 디렉터리와 지정된 디렉터리의 모든 하위 디렉터리와 파일을 살펴보고 거기에있는 파일 + 폴더 수를 반환합니다.
import os
def fcount(path):
count = 0
'''Folders'''
for f in os.listdir(path):
file = os.path.join(path, f)
if os.path.isdir(file):
file_count = fcount(file)
count += file_count + 1
'''Files'''
for f in os.listdir(path):
if os.path.isfile(os.path.join(path, f)):
count += 1
return count
path = 'F:\\'
print(fcount(path))
내가 얻은 예제 출력 700
은 총 700 개의 파일과 폴더에 대한 디렉토리 F가 제공했습니다 .
지금 제가하고 싶은 것은이 코드를 사용 fcount('F:\\')
하여 set 을 호출 하고 반환하는 것입니다 (total files, folders)
.
내가 원하는 출력의 예는 다음과 같습니다 (700, 50)
. 는 700
것입니다 files + folders
과는 50
단지입니다 folders
.
이 작업을 수행하는 방법을 잘 모르겠습니다.
두 카운트를 유지하고 튜플로 반환합니다.
total_count = dir_count = 0, 0
# .. increment either as needed
return total_count, dir_count
os.listdir()
한 번만 반복 하면됩니다 . 무언가가 파일인지 디렉토리인지 이미 감지 했으므로 하나의 루프에서 구별하십시오.
def fcount(path):
total_count = dir_count = 0
for f in os.listdir(path):
file = os.path.join(path, f)
if os.path.isdir(file):
recursive_total_count, recursive_dir_count = fcount(file)
# count this directory in the total and the directory count too
total_count += 1 + recursive_total_count
dir_count += 1 + recursive_dir_count
elif if os.path.isfile(file):
total_count += 1
return file_count, total_count
path = 'F:\\'
print(fcount(path))
마지막 print()
은 카운트와 함께 튜플을 인쇄합니다. 언제든지 분할 할 수 있습니다.
total_count, dir_count = fcount(path)
print('Total:', total_count)
print('Directories:', dir_count)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다