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))])
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
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)
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))
from pathlib import Path
path = Path('.')
print(sum(1 for _ in path.glob('*'))) # Files and folders, not recursive
print(sum(1 for _ in path.glob('**/*'))) # Files and folders, recursive
print(sum(1 for x in path.glob('*') if x.is_file())) # Only files, not recursive
print(sum(1 for x in path.glob('**/*') if x.is_file())) # Only files, recursive
import os
from pathlib import Path
def count_files(rootdir):
'''counts the number of files in each subfolder in a directory'''
for path in pathlib.Path(rootdir).iterdir():
if path.is_dir():
print("There are " + str(len([name for name in os.listdir(path) \
if os.path.isfile(os.path.join(path, name))])) + " files in " + \
str(path.name))
count_files(data_dir) # data_dir is the directory you want files counted.
你应该得到一个类似这样的输出(当然,占位符改变了):
There are {number of files} files in {name of sub-folder1}
There are {number of files} files in {name of sub-folder2}