📅  最后修改于: 2023-12-03 14:51:28.096000             🧑  作者: Mango
如果你需要在一个文件夹中查找某个特定类型的文件,你可以使用Python的os和fnmatch模块来完成这个任务。
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):
filename = os.path.join(root, basename)
yield filename
for filename in find_files('/path/to/folder', '*.txt'):
print(filename)
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):
filename = os.path.join(root, basename)
yield filename
print("以下是所有查找到的txt文件:")
for filename in find_files('/path/to/folder', '*.txt'):
print(filename)
返回的markdown格式代码片段如下:
## 实现步骤
1. 导入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):
filename = os.path.join(root, basename)
yield filename
for filename in find_files('/path/to/folder', '*.txt'):
print(filename)
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):
filename = os.path.join(root, basename)
yield filename
print("以下是所有查找到的txt文件:")
for filename in find_files('/path/to/folder', '*.txt'):
print(filename)