python os查找文件
时间: 2023-10-12 21:14:54 浏览: 129
你可以使用 Python 的 os
模块中的 walk
函数来查找文件。以下是一个示例代码:
import os
def find_files(dir_path, file_extension):
"""
查找指定目录及其子目录下指定后缀名的文件
:param dir_path: 查找的目录路径
:param file_extension: 待查找的文件后缀名
:return: 文件路径列表
"""
file_list = []
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.endswith(file_extension):
file_list.append(os.path.join(root, file))
return file_list
你可以调用 find_files
函数来查找指定目录及其子目录下所有后缀名为 .txt
的文件,例如:
dir_path = '/path/to/search'
file_extension = '.txt'
file_list = find_files(dir_path, file_extension)
print(file_list)
相关问题
python os读取文件路径
Python的os模块提供了一系列操作文件和目录的方法。要读取文件路径,你可以使用不同的函数:
获取当前路径及其信息[^1]:
- 获取当前工作目录(包括文件名):
file_name = os.path.basename(os.getcwd())
- 获取当前工作目录下的所有文件名:
file_names = os.listdir(os.getcwd())
- 获取当前工作目录(包括文件名):
获取特定文件的路径:
- 获取当前脚本文件的绝对路径(假设
__file__
是指向脚本文件的变量):script_path = os.path.abspath(__file__)
- 获取运行该脚本所在的目录:
dir_path = os.path.dirname(script_path)
- 获取当前脚本文件的绝对路径(假设
这些方法允许你在Python程序中灵活地访问和处理文件路径。例如,如果你想从dir_path
遍历查找文件,可以使用os.path.join(dir_path, filename)
来组合目录和文件名。
python os判断文件是否存在
你可以使用Python内置的os
模块来判断文件是否存在。具体的实现方法如下:
import os
filename = 'example.txt'
if os.path.exists(filename):
print("文件存在")
else:
print("文件不存在")
在上面的例子中,我们首先定义了要查找的文件名example.txt
,然后使用os.path.exists
函数来检查该文件是否存在。如果该文件存在,则os.path.exists
函数返回True
,否则返回False
。最后,我们根据os.path.exists
函数的返回值来输出相应的结果。
相关推荐











