python读取目录下子目录
时间: 2023-11-02 22:14:03 浏览: 33
可以使用Python内置的`os`模块来读取目录下的子目录。具体可以按照以下步骤进行:
1. 使用`os`模块中的`listdir()`函数列出目标目录下的所有文件和子目录;
2. 对于每个子目录,判断是否为目录,如果是目录,则将其路径加入到一个列表中;
3. 对于每个子目录,递归地重复步骤1和步骤2。
下面是一个简单的代码示例:
```python
import os
def get_subdirs(path):
subdirs = []
for name in os.listdir(path):
full_path = os.path.join(path, name)
if os.path.isdir(full_path):
subdirs.append(full_path)
subdirs.extend(get_subdirs(full_path))
return subdirs
# 示例使用:
path = '/path/to/directory'
subdirs = get_subdirs(path)
print(subdirs)
```
这个函数会返回一个包含所有子目录路径的列表。你可以根据自己的需要修改返回值的格式和内容。
相关问题
python读取目录下的文件
您可以使用Python的os模块来读取目录下的文件。下面是一个示例代码:
```python
import os
def get_files_in_directory(directory):
files = []
for file in os.listdir(directory):
if os.path.isfile(os.path.join(directory, file)):
files.append(file)
return files
directory_path = "/path/to/directory" # 替换为您要读取的目录路径
files = get_files_in_directory(directory_path)
print(files)
```
在上面的代码中,`get_files_in_directory`函数接受一个目录路径作为参数,并返回该目录下所有文件的列表。它使用`os.listdir`函数获取目录中的所有文件和子目录,然后通过`os.path.isfile`函数判断是否为文件,将文件添加到列表中。
您需要将`/path/to/directory`替换为您实际要读取的目录路径。运行代码后,将会打印出目录中的所有文件名。
python 读取目录
在 Python 中,可以使用 `os` 模块来读取目录。具体来说,可以使用 `os.listdir()` 函数来获取目录中的所有文件和子目录的名称列表。
下面是一个示例代码:
```python
import os
# 获取当前工作目录中的所有文件和子目录
dir_path = os.getcwd()
file_names = os.listdir(dir_path)
print(file_names)
```
输出结果类似于:
```
['file1.txt', 'file2.txt', 'dir1', 'dir2']
```
其中,`os.getcwd()` 函数用于获取当前工作目录的路径,`os.listdir()` 函数则用于获取目录中的所有文件和子目录的名称列表。如果需要获取完整的文件路径,可以使用 `os.path.join()` 函数来拼接。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)