python 遍历目录或文件
生活随笔
收集整理的這篇文章主要介紹了
python 遍历目录或文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
python 遍歷目錄或文件
如果想得到某個目錄下面的所有文件名,用 python 怎么做?
先看代碼:
import os,sysdef explore(dir):for root, dirs, files in os.walk(dir):print('debug: ', root, dirs, files) # 這行用來調試,幫助理解代碼 for file in files:path = os.path.join(root, file)print(path)def main():for path in sys.argv[1:]: if os.path.isdir(path):explore(path)if __name__ == "__main__":main()假設上面的代碼保存為文件 get_dirs.py
我們實操一下。
當前目錄結構如下:
$ tree . ├── a │ └── a1 │ └── a11 ├── a.txt ├── b ├── b.txt ├── c.txt ├── get_dirs.py └── ss└── s.txt結果是:
$ python3 get_dirs.py ./ debug: ./ ['a', 'b', 'ss'] ['a.txt', 'b.txt', 'c.txt', 'get_dirs.py'] ./a.txt ./b.txt ./c.txt ./get_dirs.py debug: ./a ['a1'] [] debug: ./a/a1 ['a11'] [] debug: ./a/a1/a11 [] [] debug: ./b [] [] debug: ./ss [] ['s.txt'] ./ss/s.txt代碼解讀如下。
for root, dirs, files in os.walk(dir):print('debug: ', root, dirs, files) # 這行用來調試,幫助理解代碼 for file in files:path = os.path.join(root, file)print(path)第 1 行的 os.walk 的函數聲明為:
walk(top, topdown=True, onerror=None, followlinks=False)
參數:
- top 是你所要便利的目錄的地址
- topdown 為真,則優先遍歷 top 目錄,否則優先遍歷 top 的子目錄(默認為真)
- onerror 需要一個 callable 對象,當 walk 需要異常時,會調用
- followlinks 如果為真,則會遍歷目錄下的快捷方式(linux 下是 symbolic link)實際所指的目錄(默認為假)
os.walk 的返回值是一個生成器(generator),也就是說我們需要不斷地遍歷它,以獲得所有內容。
可以理解為 os.walk 會遍歷所有的目錄(不包括文件),每次遍歷都會返回一個三元組:(root,dirs,files)。
- root 表示當前正在遍歷的目錄
- dirs 是一個 list ,會列出 root 下所有的目錄(不包括子目錄)
- files 也是一個 list , 會列出 root 下所有的文件(不包括子目錄里的文件)
知道了這些,你再對比上面的打印結果就會豁然開朗。
代碼第 4 行,path = os.path.join(root, file)
這句是什么意思呢?其實就是把 root 和 file 拼接到一起,組成完整的文件名。
舉個例子就明白了。
>>> import os >>> os.getcwd() '/mnt/hgfs/vm_share/grep_test' >>> my_path = os.path.join(os.getcwd(), "hello") >>> print(my_path) /mnt/hgfs/vm_share/grep_test/hello參考資料
【1】python中os.walk的用法
【2】os.path.join()用法
總結
以上是生活随笔為你收集整理的python 遍历目录或文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 互联网日报 | 网易回港二次上市首日涨5
- 下一篇: 软件测试nodejs面试题,nodejs