python 读取一个目录内及其子目录的所有文件
时间: 2023-07-18 16:40:57 浏览: 52
你可以使用递归函数来实现这个功能,以下是一个示例代码:
```python
import os
def get_all_files(path):
file_list = []
for root, dirs, files in os.walk(path):
for file in files:
file_list.append(os.path.join(root, file))
return file_list
# 调用函数并传入目录路径
all_files = get_all_files('/path/to/directory')
# 打印所有文件路径
for file in all_files:
print(file)
```
在上面的代码中,`os.walk()` 函数会递归地遍历指定目录下的所有子目录,并返回每个子目录中的所有文件和目录名。我们可以使用 `os.path.join()` 函数将目录和文件名拼接成完整的文件路径,并将其添加到 `file_list` 列表中。最后,我们将 `file_list` 列表作为函数的返回值,并在主程序中打印所有文件路径。
相关问题
python读取文件目录_Python读取一个目录下所有目录和文件的方法
可以使用Python的os模块来读取一个目录下所有的目录和文件。以下是一个示例代码:
```python
import os
def get_all_files(path):
files_list = []
for root, dirs, files in os.walk(path):
for file in files:
files_list.append(os.path.join(root, file))
return files_list
path = "/path/to/dir"
all_files = get_all_files(path)
print(all_files)
```
这个函数会返回一个包含所有文件路径的列表。其中,`os.walk()`函数会递归遍历目录下的所有子目录和文件,并返回每个子目录下的所有文件。`os.path.join()`函数用于将文件路径和目录路径组合成完整的路径。
写一个python脚本,把指定目录及其子目录的txt文件合并成一个csv文件
以下是一个将指定目录及其子目录中的所有txt文件合并为一个csv文件的Python脚本示例:
```python
import os
import csv
# 指定目录
dir_path = '/path/to/directory'
# 创建CSV文件
with open('merged_file.csv', mode='w', newline='') as csv_file:
writer = csv.writer(csv_file)
# 遍历目录及其子目录
for root, _, files in os.walk(dir_path):
for file_name in files:
# 只处理txt文件
if file_name.endswith('.txt'):
file_path = os.path.join(root, file_name)
# 读取txt文件内容并写入CSV文件
with open(file_path, mode='r') as txt_file:
content = txt_file.read()
writer.writerow([file_path, content])
```
此脚本将遍历指定的目录及其子目录,查找所有扩展名为txt的文件,并将它们的路径和内容写入一个名为merged_file.csv的CSV文件中。在CSV文件中,每行包含文件路径和内容。注意,如果CSV文件不存在,该脚本将自动创建它。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)