文章背景: 工作中,有时需要遍历工作夹内的所有文件,然后可以进一步操作文件。Python中的os.walk
和os.listdir
方法都可以实现遍历文件夹的功能,下面分别进行介绍。
1 os.walk
方法
2 os.listdir
方法
os.walk
方法os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。
os.walk() 方法是一个简单易用的文件、目录遍历器,可以帮助我们高效地处理文件、目录方面的事情。
walk()方法语法格式如下:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
os.walk
方法的返回值是一个生成器(generator),也就是说我们需要不断的遍历它,来获得所有的内容。
每次遍历对象,返回的都是一个三元组(root
,dirs
,files
)。
a
内的所有目录和文件(包括子目录)的地址。
import os path = r"C:\a" for root, dirs, files in os.walk(path, topdown=True): for name in files: print(os.path.join(root, name)) for folder in dirs: print(os.path.join(root, folder)) print()
运行结果:
上述代码块中,如果把topdown
的取值改为False
,运行结果如下:
如果只想获取文件夹a
内所有文件/目录(不包括子目录)的名称,代码如下:
root, dirs, files = list(os.walk(path))[0]
print(files)
print(dirs)
['4.txt', '5.txt']
['b', 'c', 'd']
os.listdir
方法os.listdir(path) 方法用于返回指定的文件夹内所包含的文件或目录的名字的列表。
This method returns the list of all files and directories in the specified path. The return type of this method is list.
如下的代码块,实现的功能是获取文件夹a
内所有文件/目录(不包括子目录)的名称。
import os
path = r"C:\a"
print(os.listdir(path))
运行结果:
['4.txt', '5.txt', 'b', 'c', 'd']
如果只想获取文件夹a
内所有的文件(不包括目录)的名称,可以使用如下的代码块。
import os
root = r"C:\a"
file = []
for item in os.listdir(root):
if os.path.isfile(os.path.join(root, item)):
file.append(item)
print(file)
运行结果:
['4.txt', '5.txt']
参考资料
[1] python中os.walk的用法(https://www.jianshu.com/p/bbad16822eab)
[2] Python os.walk() 方法(https://www.runoob.com/python/os-walk.html)
[3] Python os.walk() Method(https://www.tutorialspoint.com/python/os_walk.htm)
[4] Python | os.listdir() method(https://www.geeksforgeeks.org/python-os-listdir-method/)
[5] Python中os.walk()的使用方法(https://zhuanlan.zhihu.com/p/149824829)