如何在Python中列出目录中的所有文件并将其添加到列表中?
当前回答
listdir()返回目录中的所有内容——包括文件和目录。
os.path的isfile()只能用于列出文件:
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
或者,os.walk()为它访问的每个目录生成两个列表——一个用于文件,一个用于目录。如果您只想要顶级目录,则可以在第一次生成时中断:
from os import walk
f = []
for (dirpath, dirnames, filenames) in walk(mypath):
f.extend(filenames)
break
或更短:
from os import walk
filenames = next(walk(mypath), (None, None, []))[2] # [] if no file
其他回答
import os
os.listdir("somedirectory")
将返回“somedirectory”中所有文件和目录的列表。
从目录及其所有子目录获取完整文件路径
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
这是我的通用函数。它返回文件路径列表而不是文件名,因为我发现这更有用。它有几个可选的参数,使其具有通用性。例如,我经常将其与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)]
一位聪明的老师曾经告诉我:
当有几种既定的方法来做某事时,没有一种方法对所有情况都有好处。
因此,我将为问题的一个子集添加一个解决方案:通常,我们只想检查文件是否匹配开始字符串和结束字符串,而不需要进入子目录。因此,我们需要一个返回文件名列表的函数,例如:
filenames = dir_filter('foo/baz', radical='radical', extension='.txt')
如果您想首先声明两个函数,可以这样做:
def file_filter(filename, radical='', extension=''):
"Check if a filename matches a radical and extension"
if not filename:
return False
filename = filename.strip()
return(filename.startswith(radical) and filename.endswith(extension))
def dir_filter(dirname='', radical='', extension=''):
"Filter filenames in directory according to radical and extension"
if not dirname:
dirname = '.'
return [filename for filename in os.listdir(dirname)
if file_filter(filename, radical, extension)]
这个解决方案可以很容易地用正则表达式来概括(如果您不希望模式总是停留在文件名的开头或结尾,您可能需要添加一个模式参数)。
我真的很喜欢adamk的回答,建议您使用来自同名模块的glob()。这允许您使用*s进行模式匹配。
但正如其他人在评论中指出的,glob()可能会被不一致的斜线方向绊倒。为了帮助实现这一点,我建议您在os.path模块中使用join()和expanduser()函数,也可以在os模块中使用getcwd()函数。
例如:
from glob import glob
# Return everything under C:\Users\admin that contains a folder called wlp.
glob('C:\Users\admin\*\wlp')
上面的情况很糟糕-路径已被硬编码,并且只能在Windows上在驱动器名称和硬编码到路径之间工作。
from glob import glob
from os.path import join
# Return everything under Users, admin, that contains a folder called wlp.
glob(join('Users', 'admin', '*', 'wlp'))
上面的方法效果更好,但它依赖于文件夹名Users,该文件夹名在Windows中常见,而在其他操作系统中不常见。它还依赖于具有特定名称admin的用户。
from glob import glob
from os.path import expanduser, join
# Return everything under the user directory that contains a folder called wlp.
glob(join(expanduser('~'), '*', 'wlp'))
这在所有平台上都非常有效。
另一个很好的例子,它可以在不同的平台上完美运行,并且做了一些不同的事情:
from glob import glob
from os import getcwd
from os.path import join
# Return everything under the current directory that contains a folder called wlp.
glob(join(getcwd(), '*', 'wlp'))
希望这些示例能帮助您了解在标准Python库模块中可以找到的一些函数的功能。
推荐文章
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架
- 要列出Pandas DataFrame列
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数