Mastering File Handling in Python: A Comprehensive Guide Part 6

Mr Stucknet
Python’s Gurus
Published in
2 min readMay 18, 2024

Directory content

With Python, you can also inspect the contents of a directory. We will show you two ways of doing this. This is the first:

# files/listing.py
from pathlib import Path

p = Path('.')
for entry in p.glob('*'):
print('File:' if entry.is_file() else 'Folder:', entry)

This snippet uses the glob() method of a Path object, applied from the current directory. We iterate on the results, each of which is an instance of a subclass of Path (PosixPath or WindowsPath, according to which OS we are running). For each entry, we inspect if it is a directory, and print accordingly. Running the code yields the following (we omitted a few results for brevity):

$ python listing.py
File: existence.py
File: fear.txt
...
Folder: compression
...
File: walking.pathlib.py
...

An alternative 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('.'):
abs_root = os.path.abspath(root)
print(abs_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 the files and directories in the current one, and it will do the same for each sub-directory.

File and directory compression

Before we leave this section, let us give you an example of how to create
a compressed file. In the source code of the book, we have two examples: one creates a .zip file, while the other one creates a tar.gz file. Python allows you to create compressed files in several different ways and formats. Here, we are going to show you how to create the most common one, ZIP:

# files/compression/zip.py
from zipfile import ZipFile
with ZipFile('example.zip', 'w') as zp:
zp.write('content1.txt')
zp.write('content2.txt')
zp.write('subfolder/content3.txt')
zp.write('subfolder/content4.txt')
with ZipFile('example.zip') as zp:
zp.extract('content1.txt', 'extract_zip')
zp.extract('subfolder/content3.txt', 'extract_zip')

In the preceding code, we import ZipFile, and then, within a context manager, we write into it four files (two of which are in a sub-folder, to show how ZIP preserves the full path). Afterward, as an example, we open the compressed file and extract a couple of files from it into the extract_zip directory. If you are interested in learning more about data compression, make sure you check out the Data Compression and Archiving section on the standard library (https://docs.python.org/3.9/library/archiving.html), where you’ll be able to learn all about this topic.

That’s it for today. See you tomorrow.

If you love my blogs consider buying me a book.

Python’s Gurus🚀

Thank you for being a part of the Python’s Gurus community!

Before you go:

  • Be sure to clap x50 time and follow the writer ️👏️️
  • Follow us: Newsletter
  • Do you aspire to become a Guru too? Submit your best article or draft to reach our audience.

--

--