Working with Files and Directories in Python

 If you’ve been learning Python for a while, there comes a point where printing to the screen is no longer enough. Real programs need to save data, read existing files, organize content inside folders, and sometimes even move or rename files automatically.

That’s where working with files and directories becomes essential.

In this guide, I’ll walk you through everything in a simple, clear, and practical way — no academic tone, no complicated explanations. Just real understanding with examples you can try yourself.


What Is a File in Python?

A file is simply a sequence of bytes stored on your system. It could be:

  • A .txt text file

  • A .csv data file

  • A .jpg image🖼️

  • Or even a program file

Python lets you read from files and write to them easily using built-in functions.


Opening a File with open()

Before doing anything with a file, you must open it.

file_object = open(filename, mode)

There are different modes you can use:

File Modes

ModeMeaning
rRead (default)
wWrite (overwrites if file exists)
aAppend (adds content at the end)
xCreate file (fails if file exists)
bBinary mode
tText mode (default)

Example:

f = open("example.txt", "w") f.close()

This creates an empty file if it doesn’t exist.


Writing to a Text File

There are two common ways to write to a file:

1. Using print()

f = open("example.txt", "w") print("Hello world!", file=f) f.close()

2. Using write()

f = open("example.txt", "w") f.write("Hello world!") f.close()

Important difference:

  • print() automatically adds a newline.

  • write() does not.

If you want print() to behave like write():

print("Hello", file=f, sep="", end="")

Reading from a Text File

There are several ways to read a file.

1. read() – Read everything

f = open("example.txt", "r") content = f.read() f.close()

Be careful with very large files. Reading everything at once can consume a lot of memory.


2. readline() – Read line by line

f = open("example.txt", "r") line = f.readline() while line: print(line) line = f.readline() f.close()

3. Using a Loop ( I prefer this way)

This is the cleanest method:

with open("example.txt", "r") as f: for line in f: print(line)

This automatically closes the file after finishing. No need to call close() manually.


Why Use with?

When you use:

with open("file.txt", "r") as f:

Python automatically handles closing the file, even if an error happens. This is safer and cleaner.

Always prefer this style.


Working with Binary Files

Binary mode is used for:

  • Images

  • Audio files

  • PDFs

  • Any non-text content

Example of writing binary data:

data = bytes(range(0, 256)) with open("binaryfile", "wb") as f: f.write(data)

To read it:

with open("binaryfile", "rb") as f: content = f.read()

Notice the b in "wb" and "rb".


File Position: tell() and seek()

Python keeps track of where you are in a file.

tell()

Returns current position.

seek(offset, origin)

Moves to another position.

Example:

with open("binaryfile", "rb") as f: f.seek(0, 2) # Go to end of file position = f.tell() print(position)

origin values:

  • 0 → From start

  • 1 → From current position

  • 2 → From end

This is useful when you need to read specific parts of large files.


Checking If a File Exists

Using os.path:

import os os.path.exists("example.txt")

Other useful checks:

os.path.isfile("example.txt") os.path.isdir("foldername") os.path.isabs("path")

Copying and Renaming Files

Python makes file management simple.

Copy a file

import shutil shutil.copy("example.txt", "copy.txt")

Rename a file

import os os.rename("copy.txt", "newname.txt")

Delete a file

os.remove("newname.txt")

Working with Directories (Folders)

Files usually live inside directories.

Create a directory

os.mkdir("myfolder")

Delete a directory

os.rmdir("myfolder")

List directory contents

os.listdir(".")

. means current directory.
.. means parent directory.


Changing Directory

os.chdir("myfolder")

This moves your working location into that folder.


Searching Files with glob()

The glob module lets you search using patterns.

import glob glob.glob("*.txt")

Pattern rules:

  • * → matches everything

  • ? → single character

  • [abc] → matches a, b, or c

  • [!abc] → matches anything except a, b, c

Example:

glob.glob("m*.txt")

Finds all files starting with “m”.


Building Paths Safely

Instead of manually writing:

"path/folder/file.txt"

Use:

os.path.join("path", "folder", "file.txt")

This ensures compatibility across Windows, Linux, and macOS.


Using pathlib (Modern Approach)

Python introduced pathlib to simplify path handling.

Example:

from pathlib import Path p = Path("folder") / "file.txt" print(p.exists())

This feels cleaner and more readable.


Final Thoughts

Learning file and directory handling in Python unlocks real programming power. Once you understand how to:

  • Open files

  • Write data

  • Read content safely

  • Manage folders

  • Search and manipulate paths

You move from beginner scripts to real-world applications.

Everything from data analysis to web apps and automation depends on file handling.

Start small. Create a text file. Write to it. Read from it. Then move into directories and file operations. The more you practice, the more natural it becomes.


                     GOOD LUCK BUDDY (:

Comments

Popular posts from this blog

What I Learned About Linux Server Deployment (The Things No One Explains Clearly)

Understanding HTML Links, Structure, and Layout

How Python Really Handles Strings, Unicode, and Data