import os folder_list = ['/path/to/folder1', '/path/to/folder2', '/path/to/folder3'] for folder_path in folder_list: for sub_folder in os.listdir(folder_path): sub_folder_path = os.path.join(folder_path, sub_folder) if os.path.isdir(sub_folder_path): for file_name in os.listdir(sub_folder_path): file_path = os.path.join(sub_folder_path, file_name) if os.path.isfile(file_path): print('{}\t{}'.format(os.path.basename(os.path.dirname(folder_path)), file_name))将这个代码修改,只读取txt格式的文件
时间: 2024-03-20 18:43:15 浏览: 81
好的,以下是修改后的 Python 代码:
```python
import os
folder_list = ['/path/to/folder1', '/path/to/folder2', '/path/to/folder3']
for folder_path in folder_list:
for sub_folder in os.listdir(folder_path):
sub_folder_path = os.path.join(folder_path, sub_folder)
if os.path.isdir(sub_folder_path):
for file_name in os.listdir(sub_folder_path):
file_path = os.path.join(sub_folder_path, file_name)
if os.path.isfile(file_path) and file_name.endswith('.txt'):
print('{}\t{}'.format(os.path.basename(os.path.dirname(folder_path)), file_name))
```
你需要将代码中的 `/path/to/folder1`、`/path/to/folder2` 和 `/path/to/folder3` 替换成你想要遍历的文件夹路径列表,然后运行即可。代码会遍历所有子文件夹,只读取其中的 txt 格式文件,并输出一列来显示文件属于哪个一级文件夹,只显示出一级文件夹。
阅读全文