Answers:
原始答案:
import os
for filename in os.listdir(directory):
if filename.endswith(".asm") or filename.endswith(".py"):
# print(os.path.join(directory, filename))
continue
else:
continue
上面答案的Python 3.6版本,使用os
-假设您将目录路径作为str
对象包含在名为的变量中directory_in_str
:
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))
continue
else:
continue
或递归使用pathlib
:
from pathlib import Path
pathlist = Path(directory_in_str).glob('**/*.asm')
for path in pathlist:
# because path is object not string
path_in_str = str(path)
# print(path_in_str)
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)) continue else: continue
print(os.path.join(directory, filename))
需要更改以print(os.path.join(directory_in_str, filename))
使其在python 3.6中工作
for entry in os.scandir(path): print(entry.path)
if filename.endswith((".asm", ".py")):
到if filename.endswith(".asm") or filename.endswith(".py"):
这将遍历所有后代文件,而不仅仅是目录的直接子级:
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)
从Python 3.5开始,使用os.scandir()可以轻松得多
with os.scandir(path) as it:
for entry in it:
if entry.name.endswith(".asm") and entry.is_file():
print(entry.name, entry.path)
使用scandir()而不是listdir()可以显着提高还需要文件类型或文件属性信息的代码的性能,因为如果操作系统在扫描目录时提供了os.DirEntry对象,则os.DirEntry对象将公开此信息。所有的os.DirEntry方法都可以执行系统调用,但是is_dir()和is_file()通常只需要系统调用即可进行符号链接。os.DirEntry.stat()在Unix上始终需要系统调用,而在Windows上只需要一个系统调用即可。
这是我遍历Python中文件的方式:
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
这些技术均无法保证任何迭代顺序
是的,超级变幻莫测。请注意,我对文件名进行了排序,这在文件顺序很重要的情况下很重要,例如,对于视频帧或与时间有关的数据收集。不过,请务必在文件名中添加索引!
from pkg_resources import parse_version
并 filenames.sort(key=parse_version)
做到了。
您可以使用glob来引用目录和列表:
import glob
import os
#to get the current working directory name
cwd = 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)
要获取数组中所有目录的列表,可以使用os:
os.listdir(directory)
我对该实现还不太满意,我想拥有一个自定义构造函数,DirectoryIndex._make(next(os.walk(input_path)))
该构造函数可以使您只传递要为其列出文件的路径。欢迎编辑!
import collections
import os
DirectoryIndex = collections.namedtuple('DirectoryIndex', ['root', 'dirs', 'files'])
for file_name in DirectoryIndex(*next(os.walk('.'))).files:
file_path = os.path.join(path, file_name)