Python 实现获取文件夹下所有文件名,包括子文件下的文件名,并保存到txt
时间: 2023-07-16 16:16:15 浏览: 54
可以使用递归实现获取文件夹下所有文件名,并将结果保存到txt文件中。
以下是一个示例代码:
```python
import os
def get_all_files(path):
result = []
for root, dirs, files in os.walk(path):
for file in files:
result.append(os.path.join(root, file))
return result
all_files = get_all_files('/path/to/folder')
with open('file_list.txt', 'w') as f:
for file in all_files:
f.write(file + '\n')
```
这段代码中,`get_all_files`函数使用`os.walk`遍历指定路径下的所有文件和文件夹,并将文件名存储在列表`result`中。最后,将`result`列表中的文件名逐行写入到`file_list.txt`文件中。
相关问题
Python 实现获取文件夹下所有文件名,包括子文件下的文件名
可以使用 Python 的 `os` 和 `os.path` 模块来实现获取文件夹下所有文件名,包括子文件下的文件名。具体实现过程如下:
```python
import os
# 定义一个函数,传入文件夹路径,返回该文件夹下所有文件名(包括子文件夹下的文件)
def get_all_files(dir_path):
files_list = []
for root, dirs, files in os.walk(dir_path):
for file in files:
files_list.append(os.path.join(root, file))
return files_list
# 测试函数
dir_path = "/path/to/folder"
all_files = get_all_files(dir_path)
print(all_files)
```
解释一下代码:
- `os.walk(dir_path)` 可以遍历指定文件夹下的所有子文件夹和文件,返回一个三元组 `(root, dirs, files)`,其中 `root` 表示当前文件夹路径,`dirs` 表示当前文件夹下的子文件夹列表,`files` 表示当前文件夹下的文件列表。
- `os.path.join(root, file)` 可以将当前文件的路径与根路径拼接起来,形成完整的文件路径。
- 最后将所有文件路径保存在 `files_list` 列表中,并返回该列表。
注意:如果文件夹路径不存在,会抛出 `FileNotFoundError` 异常。
python获取文件夹下所有文件名,并保存在txt文件内
可以使用Python中的os模块和glob模块来实现获取文件夹下所有文件名,并保存在txt文件内的功能。
以下是示例代码:
```python
import os
import glob
# 获取文件夹路径
folder_path = '/path/to/folder'
# 获取文件夹下所有文件名
file_names = glob.glob(os.path.join(folder_path, '*'))
# 将文件名保存在txt文件内
with open('file_names.txt', 'w') as f:
for file_name in file_names:
f.write(file_name + '\n')
```
在代码中,我们首先指定了要获取文件名的文件夹路径,然后使用glob模块的glob函数和os模块的join函数获取文件夹下所有文件名。最后,我们将文件名保存在名为file_names.txt的txt文件中。注意,我们使用了with语句来打开文件并在操作完成后自动关闭文件。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)