os.walk os.listdir
时间: 2023-09-09 20:09:50 浏览: 115
Python使用os.listdir和os.walk获取文件路径
5星 · 资源好评率100%
`os.walk` and `os.listdir` are both Python functions used to traverse directories and retrieve information about the files and subdirectories within them.
`os.walk` is a generator function that returns a tuple of three values for each directory it traverses: the path of the directory, a list of the subdirectories within that directory, and a list of the files within that directory. This function is often used to recursively traverse a directory tree and perform operations on all the files and directories within it.
Here's an example of using `os.walk` to print out the names of all the files in a directory tree:
```
import os
root_dir = '/path/to/root/dir'
for dirpath, dirnames, filenames in os.walk(root_dir):
for filename in filenames:
print(os.path.join(dirpath, filename))
```
`os.listdir`, on the other hand, is a simpler function that returns a list of all the files and directories within a given directory. It does not recursively traverse subdirectories, but only returns the names of the files and directories within the specified directory.
Here's an example of using `os.listdir` to print out the names of all the files in a directory:
```
import os
dir_path = '/path/to/dir'
for filename in os.listdir(dir_path):
if os.path.isfile(os.path.join(dir_path, filename)):
print(filename)
```
阅读全文