王尘宇王尘宇

研究百度干SEO做推广变成一个被互联网搞的人

python目录下所有文件名(python获取目录下文件路径)

 

获取目录中所有文件和文件夹是Python中文件相关最基本的操作,具体操作举例如下。

文件操作将从创建一个Path对象开始,在Windows上,您将获得一个WindowsPath对象。

>>> import pathlib
>>> desktop = pathlib.Path("D:/temp")
>>> desktop
WindowsPath('D:/temp')

如果你只需要列出给定目录的内容,而不需要获取每个子目录的内容,那么你可以使用Path对象的.iterdir()方法,并使用列表list()进行显示。

>>> import pathlib
>>> desktop = pathlib.Path("D:/temp")
>>> desktop.iterdir()
<generator object Path.iterdir at 0x0000000002C8EF90>
>>> list(desktop.iterdir())
[WindowsPath('D:/temp/Python'), WindowsPath('D:/temp/python.rar'), WindowsPath('D:/temp/python.txt')]

也可以使用for循环来迭代生成的每个项目。

>>> for item in desktop.iterdir():
              print(f"{item} - {'dir' if item.is_dir() else 'file'}")

D: \temp\Python - dir
D: \temp\python.rar - file
D: \temp\python.txt - file

可以使用.is_dir()、is_file()方法进行判断,有选择的列出文件或文件夹。

>>> for item in desktop.iterdir():
              if item.is_file():
                  print(item)

D: \temp\python.rar
D:\temp\python.txt

使用.rglob()递归列出子文件夹中的文件夹及文件。

>>> desktop.rglob("*")
<generator object Path.rglob at 0x0000000002C8EF20>
>>> list(desktop.rglob("*"))
[WindowsPath('D:/temp/Python'),
 WindowsPath('D:/temp/python.rar'),
 WindowsPath('D:/temp/python.txt'), 
 WindowsPath('D:/temp/Python/vector.py')]

相关文章

评论列表

发表评论:
验证码

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。