python2.7 在指定目录下 查询指定后缀文件的全路径
时间: 2023-12-06 12:44:31 浏览: 35
可以使用 Python 的 `os` 模块和 `fnmatch` 模块来实现,在指定目录下递归查找指定后缀的文件,并返回其全路径列表。示例代码如下:
```python
import os
import fnmatch
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
yield os.path.join(root, basename)
# 在当前目录下查找所有的 .txt 文件
files = list(find_files('.', '*.txt'))
print(files)
```
其中,`os.walk()` 函数可以递归查找指定目录下的所有文件和子目录,`fnmatch.fnmatch()` 函数可以使用通配符匹配指定文件名。上述代码将返回当前目录下所有的后缀为 `.txt` 的文件的全路径列表。
相关问题
python2.7 在指定目录下 查询 部分文件名 文件的全路径
你可以使用 `os` 和 `fnmatch` 模块来实现在指定目录下查询部分文件名的文件全路径,具体代码如下:
```python
import os
import fnmatch
# 指定目录路径和文件名的部分字符串
directory = '/path/to/directory'
file_pattern = '*part_of_filename*'
# 遍历目录下的所有文件并筛选符合条件的文件
for root, dirs, files in os.walk(directory):
for filename in fnmatch.filter(files, file_pattern):
# 输出符合条件的文件的全路径
print(os.path.abspath(os.path.join(root, filename)))
```
其中,`os.walk()` 函数会遍历指定目录下的所有文件和子目录,`fnmatch.filter()` 函数用于筛选符合条件的文件,`os.path.abspath()` 函数用于获取文件的绝对路径。
python 2.7 扫描指定目录下的文件是否包含 html 文件,并打印路径
可以使用 Python 的 os 模块和 fnmatch 模块来扫描指定目录下的文件并判断是否包含 html 文件,示例代码如下:
```python
import os
import fnmatch
root_path = "/path/to/directory"
for root, dirnames, filenames in os.walk(root_path):
for filename in fnmatch.filter(filenames, "*.html"):
file_path = os.path.join(root, filename)
print(file_path)
```
上述代码中,首先定义了要扫描的根目录 root_path,然后使用 os.walk 函数遍历该目录下的所有子目录和文件,并使用 fnmatch.filter 函数过滤出所有以 .html 结尾的文件名,最后将文件路径拼接起来并打印出来。