Directory content

With Python, you can also inspect the content of a directory. I'll show you two ways of doing this:

# files/listing.py
import os

with os.scandir('.') as it:
for entry in it:
print(
entry.name, entry.path,
'File' if entry.is_file() else 'Folder'
)

This snippet uses os.scandir, called on the current directory. We iterate on the results, each of which is an instance of os.DirEntry, a nice class that exposes useful properties and methods. In the code, we access a subset of those: name, path, and is_file(). Running the code yields the following (I omitted a few results for brevity):

$ python listing.py
fixed_amount.py ./fixed_amount.py File
existence.py ./existence.py File
...
ops_example ./ops_example Folder
...

A more powerful way to scan a directory tree is given to us by os.walk. Let's see an example:

# files/walking.py
import os

for root, dirs, files in os.walk('.'):
print(os.path.abspath(root))
if dirs:
print('Directories:')
for dir_ in dirs:
print(dir_)
print()
if files:
print('Files:')
for filename in files:
print(filename)
print()

Running the preceding snippet will produce a list of all files and directories in the current one, and it will do the same for each sub-directory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.162.201