如何在Python中列出目录中的所有文件并将其添加到列表中?
当前回答
使用发电机
import os
def get_files(search_path):
for (dirpath, _, filenames) in os.walk(search_path):
for filename in filenames:
yield os.path.join(dirpath, filename)
list_files = get_files('.')
for filename in list_files:
print(filename)
其他回答
这是我的通用函数。它返回文件路径列表而不是文件名,因为我发现这更有用。它有几个可选的参数,使其具有通用性。例如,我经常将其与pattern=“*.txt”或subfolders=True等参数一起使用。
import os
import fnmatch
def list_paths(folder='.', pattern='*', case_sensitive=False, subfolders=False):
"""Return a list of the file paths matching the pattern in the specified
folder, optionally including files inside subfolders.
"""
match = fnmatch.fnmatchcase if case_sensitive else fnmatch.fnmatch
walked = os.walk(folder) if subfolders else [next(os.walk(folder))]
return [os.path.join(root, f)
for root, dirnames, filenames in walked
for f in filenames if match(f, pattern)]
我更喜欢使用glob模块,因为它可以进行模式匹配和扩展。
import glob
print(glob.glob("/home/adam/*"))
它可以直观地进行模式匹配
import glob
# All files and directories ending with .txt and that don't begin with a dot:
print(glob.glob("/home/adam/*.txt"))
# All files and directories ending with .txt with depth of 2 folders, ignoring names beginning with a dot:
print(glob.glob("/home/adam/*/*.txt"))
它将返回一个包含查询文件和目录的列表:
['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]
注意,glob忽略以点开头的文件和目录。,因为这些被认为是隐藏的文件和目录,除非模式类似于.*。
使用glob.escape转义不应该是模式的字符串:
print(glob.glob(glob.escape(directory_name) + "/*.txt"))
dircache是“自2.6版以来已弃用:Python 3.0中已删除dircache模块。”
import dircache
list = dircache.listdir(pathname)
i = 0
check = len(list[0])
temp = []
count = len(list)
while count != 0:
if len(list[i]) != check:
temp.append(list[i-1])
check = len(list[i])
else:
i = i + 1
count = count - 1
print temp
从目录及其所有子目录获取完整文件路径
import os
def get_filepaths(directory):
"""
This function will generate the file names in a directory
tree by walking the tree either top-down or bottom-up. For each
directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
"""
file_paths = [] # List which will store all of the full filepaths.
# Walk the tree.
for root, directories, files in os.walk(directory):
for filename in files:
# Join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath) # Add it to the list.
return file_paths # Self-explanatory.
# Run the above function and store its results in a variable.
full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST")
我在上述函数中提供的路径包含3个文件,其中两个位于根目录中,另一个位于名为“subfolder”的子文件夹中打印将打印列表的完整文件路径:['/Users/johnny/Desktop/TEST/file1.txt','/Users/johnny/Desctop/TEST-file2.txt','/Users/johnny/Desktop/STEST/SUBFOLDER/file3.dat']
如果愿意,您可以打开并阅读内容,或者只关注扩展名为“.dat”的文件,如下面的代码所示:
for f in full_file_paths:
if f.endswith(".dat"):
print f
/用户/johnny/Desktop/TEST/SUBFOLDER/file3.dat
返回绝对文件路径列表,不会递归到子目录
L = [os.path.join(os.getcwd(),f) for f in os.listdir('.') if os.path.isfile(os.path.join(os.getcwd(),f))]
推荐文章
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 如何从查找“类型d”中排除此/ current / dot文件夹
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列
- 熊猫在每组中获得最高的n个记录