Python 3 simple ways to list files and folders

Опубликовано: 06 Октябрь 2024
на канале: Softhints - Python, Linux, Pandas
2,628
18

Python 3 simple ways to list files in a folder

http://blog.softhints.com/python-simp...


os.scandir() - since Python 3.5. It is advertised as PEP 471 -- os.scandir() function -- a better and faster directory iterator

import os
my_files = [f.name for f in os.scandir() if f.is_file()]
print(my_files)

os.listdir() - compatible with python 2.7 which make it good if you need to list files in both version Python 2 and 3

import os
my_files = os.listdir()
print(my_files)


os.walk() - method for recursive iteration of files and folders in a given directory

import os

for r, d, f in os.walk('/tmp/test'):
for file in f:
if ".bak" in file:
print(os.path.join(r, file)


---------------------------------------------------------------------------------------------------------------------------------------------------------------
Code store

https://bitbucket.org/softhints/

Socials

Facebook:   / 435421910242028  
Facebook:   / softhints  
Twitter:   / softwarehints  
Discord:   / discord  


If you really find this channel useful and enjoy the content, you're welcome to support me and this channel with a small donation via PayPal.

PayPal donation https://www.paypal.me/fantasyan