Kako prečkati datotečni sistem v Pythonu? Recimo, da smo podali spodnjo strukturo datoteke v našem sistemu in želimo v celoti prečkati vse njegove veje od zgoraj navzdol?
Kako os.walk() deluje v pythonu?
OS.walk() ustvari imena datotek v drevesu imenikov s sprehodom po drevesu od zgoraj navzdol ali od spodaj navzgor. Za vsak imenik v drevesu, ukoreninjen na vrhu imenika (vključno s samim vrhom), dobi 3-tuple (dirpath, dirnames, filenames).
- koren: Natisne samo imenike iz tistega, kar ste določili.
- reci: Natisne podimenike iz korena.
- datoteke: Natisne vse datoteke iz korena in imenikov.
# Driver function import os if __name__ == "__main__": for (root,dirs,files) in os.walk('.', topdown=True): print (root) print (dirs) print (files) print ('--------------------------------')>
Izhod:
['gfg-article-deep-crawl-master (1)', '.ipynb_checkpoints'] ['t.pdf', 'Untitled.ipynb'] -------------------------------- ./gfg-article-deep-crawl-master (1) ['gfg-article-deep-crawl-master'] [] -------------------------------- ./gfg-article-deep-crawl-master (1)/gfg-article-deep-crawl-master ['check_rank'] ['rank_scraper.py', 'search-page (copy).html', '.gitignore', 'search-page.html', 'globals.py', 'requirements.txt', 'sel_scraper.py', 'README.md'] -------------------------------- ./gfg-article-deep-crawl-master (1)/gfg-article-deep-crawl-master/check_rank [] ['selenium.py', 'tools.py', '__init__.py', 'run_check.py'] -------------------------------- ./.ipynb_checkpoints [] ['Untitled-checkpoint.ipynb'] -------------------------------->
Razumevanje ugnezdenih seznamov z Os.Walk
Program za iskanje datotek python v drevesu imenikov, kar pomeni, da moramo najti datoteke, ki se končajo s pripono .py.
Python # code import os if __name__ == '__main__': pythonFiles = [file for dirs in os.walk('.', topdown=True) for file in dirs[2] if file.endswith('.py')] print('python files in the directory tree are ') for r in pythonFiles: print(r)>
Izhod
python files in the directory tree are Solution.py>