Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions working-with-files-in-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Working With Files in Python

This folder provides the code examples for the Real Python tutorial [Working With Files in Python](https://realpython.com/working-with-files-in-python/).

## Setup

You need Python 3.12 or later. Everything in this folder uses the standard library, so there's nothing to install. A few examples need a newer Python, and the scripts skip them on older versions:

- `Path.copy()`, `Path.move()`, and Zstandard-compressed TAR archives need Python 3.14 or later.
- The `parent_mode` argument of `os.makedirs()` needs Python 3.15 or later.

Run the scripts from inside this folder. First, create the sample directories that the examples work on:

```console
$ python make_fixtures.py
Created my_directory/
Created some_directory/
Created walk_directory/
Created data/
```

Run `make_fixtures.py` again at any time to reset the sample directories.

## Usage

Each script covers one section of the tutorial:

| Script | Tutorial section |
|---|---|
| `list_directory.py` | Getting a Directory Listing |
| `file_attributes.py` | Getting File Attributes |
| `make_directories.py` | Making Directories |
| `pattern_matching.py` | Filename Pattern Matching |
| `traverse_directories.py` | Traversing Directories and Processing Files |
| `temporary_files.py` | Making Temporary Files and Directories |
| `delete_files.py` | Deleting Files and Directories |
| `copy_move_rename.py` | Copying, Moving, and Renaming Files and Directories |
| `zip_archives.py` | Reading, Extracting, and Creating ZIP Archives |
| `tar_archives.py` | Opening, Extracting, and Creating TAR Archives |
| `shutil_archives.py` | An Easier Way of Creating Archives |
| `fileinput-example.py` | Reading Multiple Files |

For example:

```console
$ python pattern_matching.py
$ python fileinput-example.py bacon.txt cupcake.txt
```

The scripts that create, delete, or archive files work on their own sample files or in scratch folders (`zip_workspace/`, `tar_workspace/`), so they don't touch anything else on your computer. Directory listings come back in an order that depends on your filesystem, so your output may be sorted differently from the tutorial's.
7 changes: 7 additions & 0 deletions working-with-files-in-python/bacon.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Spicy jalapeno bacon ipsum dolor amet in in aute est qui enim aliquip,
irure cillum drumstick elit.
Doner jowl shank ea exercitation landjaeger incididunt ut porchetta.
Tenderloin bacon aliquip cupidatat chicken chuck quis anim et swine.
Tri-tip doner kevin cillum ham veniam cow hamburger.
Turkey pork loin cupidatat filet mignon capicola brisket cupim ad in.
Ball tip dolor do magna laboris nisi pancetta nostrud doner.
46 changes: 46 additions & 0 deletions working-with-files-in-python/copy_move_rename.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import os
import shutil
import sys
from pathlib import Path

# Start from a clean slate so that the script can run more than once.
for name in ["path", "data_1", "data1_backup", "dir_1", "backup", "data_2"]:
shutil.rmtree(name, ignore_errors=True)
for name in ["first.zip", "first_01.zip", "data_01.txt", "data.txt"]:
Path(name).unlink(missing_ok=True)

Path("path/to/dest_dir").mkdir(parents=True)
Path("path/to/file.txt").write_text("some data\n")
Path("data_1").mkdir()
Path("data_1/notes.txt").write_text("some notes\n")
Path("dir_1").mkdir()
Path("first.zip").touch()
Path("data_01.txt").touch()

# Copying files
src = "path/to/file.txt"
dst = "path/to/dest_dir"
print(shutil.copy(src, dst))
print(shutil.copy2(src, dst))

# Copying directories
print(repr(shutil.copytree("data_1", "data1_backup")))

# Moving files and directories
print(repr(shutil.move("dir_1/", "backup/")))

# Renaming files and directories
os.rename("first.zip", "first_01.zip")
data_file = Path("data_01.txt")
print(repr(data_file.rename("data.txt")))

# Copying and moving with pathlib requires Python 3.14 or later
if sys.version_info >= (3, 14):
print(repr(Path("data_1").copy("data_2")))
print(repr(Path("data_2").move("backup/data_2")))

# Clean up
for name in ["path", "data_1", "data1_backup", "backup"]:
shutil.rmtree(name)
for name in ["first_01.zip", "data.txt"]:
os.remove(name)
3 changes: 3 additions & 0 deletions working-with-files-in-python/cupcake.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Cupcake ipsum dolor sit amet candy I love cheesecake fruitcake.
Topping muffin cotton candy.
Gummies macaroon jujubes jelly beans marzipan.
61 changes: 61 additions & 0 deletions working-with-files-in-python/delete_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import os
import shutil
from pathlib import Path

# Set up a few files and folders to delete
Path("home").mkdir(exist_ok=True)
Path("home/data.txt").write_text("some data\n")
Path("my_documents/bad_dir").mkdir(parents=True, exist_ok=True)
Path("my_documents/bad_dir/notes.txt").write_text("not empty\n")

data_file = "home/data.txt"

# If the file exists, delete it
if os.path.isfile(data_file):
os.remove(data_file)
else:
print(f"Error: {data_file} not a valid filename")

# Use exception handling
try:
os.remove(data_file)
except OSError as e:
print(f"Error: {data_file} : {e.strerror}")

data_file = Path("home/data.txt")
try:
data_file.unlink()
except OSError as e:
print(f"Error: {data_file} : {e.strerror}")

data_file.unlink(missing_ok=True)

# os.rmdir() and Path.rmdir() only delete empty directories
trash_dir = "my_documents/bad_dir"
try:
os.rmdir(trash_dir)
except OSError as e:
print(f"Error: {trash_dir} : {e.strerror}")

trash_dir = Path("my_documents/bad_dir")
try:
trash_dir.rmdir()
except OSError as e:
print(f"Error: {trash_dir} : {e.strerror}")

# shutil.rmtree() deletes a whole tree
trash_dir = "my_documents/bad_dir"
try:
shutil.rmtree(trash_dir)
except OSError as e:
print(f"Error: {trash_dir} : {e.strerror}")

# Delete empty folders recursively, bottom-up
for dirpath, dirnames, files in os.walk("my_documents", topdown=False):
try:
os.rmdir(dirpath)
except OSError:
pass

os.rmdir("home")
print("my_documents still exists:", os.path.exists("my_documents"))
36 changes: 36 additions & 0 deletions working-with-files-in-python/file_attributes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import os
from datetime import datetime, timezone
from os import scandir
from pathlib import Path


def convert_date(timestamp):
d = datetime.fromtimestamp(timestamp, tz=timezone.utc)
formatted_date = d.strftime("%d %b %Y")
return formatted_date


def get_files():
dir_entries = scandir("my_directory/")
for entry in dir_entries:
if entry.is_file():
info = entry.stat()
date = convert_date(info.st_mtime)
print(f"{entry.name}\t Last Modified: {date}")


if __name__ == "__main__":
print("--- st_mtime with os.scandir() ---")
with os.scandir("my_directory/") as dir_contents:
for entry in dir_contents:
info = entry.stat()
print(info.st_mtime)

print("\n--- st_mtime with pathlib ---")
current_dir = Path("my_directory")
for path in current_dir.iterdir():
info = path.stat()
print(info.st_mtime)

print("\n--- get_files() ---")
get_files()
8 changes: 8 additions & 0 deletions working-with-files-in-python/fileinput-example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import fileinput

files = fileinput.input()
for line in files:
if fileinput.isfirstline():
print(f"\n--- Reading {fileinput.filename()} ---")
print(" -> " + line, end="")
print()
57 changes: 57 additions & 0 deletions working-with-files-in-python/list_directory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import os
from pathlib import Path

basepath = "my_directory/"

print("--- os.listdir() ---")
for entry in os.listdir(basepath):
print(entry)

print("\n--- os.scandir() ---")
with os.scandir(basepath) as entries:
for entry in entries:
print(entry.name)

print("\n--- pathlib.Path.iterdir() ---")
entries = Path(basepath)
for entry in entries.iterdir():
print(entry.name)

print("\n--- Files only: os.listdir() and os.path ---")
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, entry)):
print(entry)

print("\n--- Files only: os.scandir() ---")
with os.scandir(basepath) as entries:
for entry in entries:
if entry.is_file():
print(entry.name)

print("\n--- Files only: pathlib ---")
for item in Path(basepath).iterdir():
if item.is_file():
print(item.name)

print("\n--- Files only: generator expression ---")
files_in_basepath = (
entry for entry in Path(basepath).iterdir() if entry.is_file()
)
for item in files_in_basepath:
print(item.name)

print("\n--- Subdirectories: os.listdir() and os.path ---")
for entry in os.listdir(basepath):
if os.path.isdir(os.path.join(basepath, entry)):
print(entry)

print("\n--- Subdirectories: os.scandir() ---")
with os.scandir(basepath) as entries:
for entry in entries:
if entry.is_dir():
print(entry.name)

print("\n--- Subdirectories: pathlib ---")
for entry in Path(basepath).iterdir():
if entry.is_dir():
print(entry.name)
43 changes: 43 additions & 0 deletions working-with-files-in-python/make_directories.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import os
import pathlib
import shutil
import stat
import sys
from pathlib import Path

# Start from a clean slate so that the script can run more than once.
for name in ["example_directory", "2018"]:
shutil.rmtree(name, ignore_errors=True)

# Create a single directory
os.mkdir("example_directory/")

p = Path("example_directory")
try:
p.mkdir()
except FileExistsError as exc:
print(exc)

p.mkdir(exist_ok=True)

# Create a directory tree with a restricted mode for the leaf directory
os.makedirs("2018/10/05", mode=0o770)
for path in ["2018", "2018/10", "2018/10/05"]:
print(stat.filemode(os.stat(path).st_mode), path)

# Python 3.15 added parent_mode for the intermediate directories
if sys.version_info >= (3, 15):
shutil.rmtree("2018")
os.makedirs("2018/10/05", mode=0o770, parent_mode=0o770)
for path in ["2018", "2018/10", "2018/10/05"]:
print(stat.filemode(os.stat(path).st_mode), path)

# Create a directory tree with pathlib
shutil.rmtree("2018")
p = pathlib.Path("2018/10/05")
p.mkdir(parents=True)
print(f"Created {p}")

# Clean up
shutil.rmtree("example_directory")
shutil.rmtree("2018")
65 changes: 65 additions & 0 deletions working-with-files-in-python/make_fixtures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""Create the sample directories that the tutorial's examples work on.

Run this script first, from inside this folder. Running it again resets
the sample directories to their original state.
"""

import shutil
from pathlib import Path

FIXTURES = {
"my_directory": [
"sub_dir/bar.py",
"sub_dir/foo.py",
"sub_dir_b/file4.txt",
"sub_dir_c/config.py",
"sub_dir_c/file5.txt",
"file1.py",
"file2.csv",
"file3.txt",
],
"some_directory": [
"sub_dir/file1.py",
"sub_dir/file2.py",
"admin.py",
"data_01_backup.txt",
"data_01.txt",
"data_02_backup.txt",
"data_02.txt",
"data_03_backup.txt",
"data_03.txt",
"tests.py",
],
"walk_directory": [
"folder_1/file1.py",
"folder_1/file2.py",
"folder_1/file3.py",
"folder_2/file4.py",
"folder_2/file5.py",
"folder_2/file6.py",
"test1.txt",
"test2.txt",
],
"data": [
"sub_dir/bar.py",
"sub_dir/foo.py",
"file1.py",
"file2.py",
"file3.py",
],
}


def make_fixtures(base=Path(".")):
for directory, files in FIXTURES.items():
root = base / directory
shutil.rmtree(root, ignore_errors=True)
for name in files:
path = root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(f"# {name}\n")
print(f"Created {root}/")


if __name__ == "__main__":
make_fixtures()
Loading
Loading