import os
directory = os.fsencode(directory_in_str)
for file in os.listdir(directory):filename = os.fsdecode(file)if filename.endswith(".asm") or filename.endswith(".py"):# print(os.path.join(directory, filename))continueelse:continue
from pathlib import Path
pathlist = Path(directory_in_str).glob('**/*.asm')for path in pathlist:# because path is object not stringpath_in_str = str(path)# print(path_in_str)
from pathlib import Path
pathlist = Path(directory_in_str).rglob('*.asm')for path in pathlist:# because path is object not stringpath_in_str = str(path)# print(path_in_str)
原答复:
import os
for filename in os.listdir("/path/to/dir/"):if filename.endswith(".asm") or filename.endswith(".py"):# print(os.path.join(directory, filename))continueelse:continue
import os
for subdir, dirs, files in os.walk(rootdir):for file in files:#print os.path.join(subdir, file)filepath = subdir + os.sep + file
if filepath.endswith(".asm"):print (filepath)
import os
path = 'the/name/of/your/path'
folder = os.fsencode(path)
filenames = []
for file in os.listdir(folder):filename = os.fsdecode(file)if filename.endswith( ('.jpeg', '.png', '.gif') ): # whatever file types you're using...filenames.append(filename)
filenames.sort() # now you have the filenames and can do something with them
import os
i = 0with os.scandir('/usr/local/bin') as root_dir:for path in root_dir:if path.is_file():i += 1print(f"Full path is: {path} and just the name is: {path.name}")print(f"{i} files scanned successfully.")
import globimport os
#to get the current working directory namecwd = os.getcwd()#Load the images from images folder.for f in glob.glob('images\*.jpg'):dir_name = get_dir_name(f)image_file_name = dir_name + '.jpg'#To print the file name with path (path will be in string)print (image_file_name)
import os
path = "path_to_file"file_type = '.asm'
for filename in os.listdir(path=path):if filename.endswith(file_type):print(filename)print(f"{path}/{filename}")# do something below
import osDIRECTORY_TO_LOOP = '/var/www/files/'for root, dirs, files in os.walk(DIRECTORY_TO_LOOP, topdown=False):for name in files:print(os.path.join(root, name))