From 8f506cc342b66dbabfb6ee8c7fe25a2465515197 Mon Sep 17 00:00:00 2001 From: Real Python Bot <42617967+realpython-bot@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:28:02 +0000 Subject: [PATCH 1/2] Add working-with-files-in-python materials folder Co-Authored-By: Claude Opus 5.5 --- working-with-files-in-python/README.md | 50 +++++++++++ working-with-files-in-python/bacon.txt | 7 ++ .../copy_move_rename.py | 46 ++++++++++ working-with-files-in-python/cupcake.txt | 3 + working-with-files-in-python/delete_files.py | 61 +++++++++++++ .../file_attributes.py | 37 ++++++++ .../fileinput-example.py | 8 ++ .../list_directory.py | 57 ++++++++++++ .../make_directories.py | 43 +++++++++ working-with-files-in-python/make_fixtures.py | 65 ++++++++++++++ .../pattern_matching.py | 35 ++++++++ .../shutil_archives.py | 9 ++ working-with-files-in-python/tar_archives.py | 89 +++++++++++++++++++ .../temporary_files.py | 29 ++++++ .../traverse_directories.py | 22 +++++ working-with-files-in-python/zip_archives.py | 61 +++++++++++++ 16 files changed, 622 insertions(+) create mode 100644 working-with-files-in-python/README.md create mode 100644 working-with-files-in-python/bacon.txt create mode 100644 working-with-files-in-python/copy_move_rename.py create mode 100644 working-with-files-in-python/cupcake.txt create mode 100644 working-with-files-in-python/delete_files.py create mode 100644 working-with-files-in-python/file_attributes.py create mode 100644 working-with-files-in-python/fileinput-example.py create mode 100644 working-with-files-in-python/list_directory.py create mode 100644 working-with-files-in-python/make_directories.py create mode 100644 working-with-files-in-python/make_fixtures.py create mode 100644 working-with-files-in-python/pattern_matching.py create mode 100644 working-with-files-in-python/shutil_archives.py create mode 100644 working-with-files-in-python/tar_archives.py create mode 100644 working-with-files-in-python/temporary_files.py create mode 100644 working-with-files-in-python/traverse_directories.py create mode 100644 working-with-files-in-python/zip_archives.py diff --git a/working-with-files-in-python/README.md b/working-with-files-in-python/README.md new file mode 100644 index 0000000000..a16372e2ed --- /dev/null +++ b/working-with-files-in-python/README.md @@ -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. diff --git a/working-with-files-in-python/bacon.txt b/working-with-files-in-python/bacon.txt new file mode 100644 index 0000000000..e569e09eee --- /dev/null +++ b/working-with-files-in-python/bacon.txt @@ -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. diff --git a/working-with-files-in-python/copy_move_rename.py b/working-with-files-in-python/copy_move_rename.py new file mode 100644 index 0000000000..67c989b8e1 --- /dev/null +++ b/working-with-files-in-python/copy_move_rename.py @@ -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) diff --git a/working-with-files-in-python/cupcake.txt b/working-with-files-in-python/cupcake.txt new file mode 100644 index 0000000000..c17c4509e9 --- /dev/null +++ b/working-with-files-in-python/cupcake.txt @@ -0,0 +1,3 @@ +Cupcake ipsum dolor sit amet candy I love cheesecake fruitcake. +Topping muffin cotton candy. +Gummies macaroon jujubes jelly beans marzipan. diff --git a/working-with-files-in-python/delete_files.py b/working-with-files-in-python/delete_files.py new file mode 100644 index 0000000000..957d0c42e8 --- /dev/null +++ b/working-with-files-in-python/delete_files.py @@ -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")) diff --git a/working-with-files-in-python/file_attributes.py b/working-with-files-in-python/file_attributes.py new file mode 100644 index 0000000000..eb8b7a08ef --- /dev/null +++ b/working-with-files-in-python/file_attributes.py @@ -0,0 +1,37 @@ +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() + print( + f"{entry.name}\t Last Modified: {convert_date(info.st_mtime)}" + ) + + +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() diff --git a/working-with-files-in-python/fileinput-example.py b/working-with-files-in-python/fileinput-example.py new file mode 100644 index 0000000000..f226f71a6c --- /dev/null +++ b/working-with-files-in-python/fileinput-example.py @@ -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() diff --git a/working-with-files-in-python/list_directory.py b/working-with-files-in-python/list_directory.py new file mode 100644 index 0000000000..ea33963234 --- /dev/null +++ b/working-with-files-in-python/list_directory.py @@ -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) diff --git a/working-with-files-in-python/make_directories.py b/working-with-files-in-python/make_directories.py new file mode 100644 index 0000000000..14b5649824 --- /dev/null +++ b/working-with-files-in-python/make_directories.py @@ -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") diff --git a/working-with-files-in-python/make_fixtures.py b/working-with-files-in-python/make_fixtures.py new file mode 100644 index 0000000000..fd5e9f583b --- /dev/null +++ b/working-with-files-in-python/make_fixtures.py @@ -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() diff --git a/working-with-files-in-python/pattern_matching.py b/working-with-files-in-python/pattern_matching.py new file mode 100644 index 0000000000..294de9d075 --- /dev/null +++ b/working-with-files-in-python/pattern_matching.py @@ -0,0 +1,35 @@ +import fnmatch +import glob +import os +from pathlib import Path + +print("--- .endswith() ---") +for f_name in os.listdir("some_directory"): + if f_name.endswith(".txt"): + print(f_name) + +print("\n--- fnmatch: *.txt ---") +for file_name in os.listdir("some_directory/"): + if fnmatch.fnmatch(file_name, "*.txt"): + print(file_name) + +print("\n--- fnmatch: data_*_backup.txt ---") +for filename in os.listdir("some_directory/"): + if fnmatch.fnmatch(filename, "data_*_backup.txt"): + print(filename) + +print("\n--- glob.glob() ---") +print(glob.glob("*.py", root_dir="some_directory")) + +for name in glob.glob("*[0-9]*.txt", root_dir="some_directory"): + print(name) + +print("\n--- glob.iglob(), recursive ---") +root = "some_directory" +for file in glob.iglob("**/*.py", recursive=True, root_dir=root): + print(file) + +print("\n--- Path.glob() ---") +p = Path("some_directory") +for name in p.glob("*.p*"): + print(name) diff --git a/working-with-files-in-python/shutil_archives.py b/working-with-files-in-python/shutil_archives.py new file mode 100644 index 0000000000..aa082a2855 --- /dev/null +++ b/working-with-files-in-python/shutil_archives.py @@ -0,0 +1,9 @@ +import os +import shutil + +# Bundle everything in data/ into backup.tar in the current directory +print(shutil.make_archive("backup", "tar", "data/")) + +# Extract the archive again +shutil.unpack_archive("backup.tar", "extract_dir/") +print(sorted(os.listdir("extract_dir"))) diff --git a/working-with-files-in-python/tar_archives.py b/working-with-files-in-python/tar_archives.py new file mode 100644 index 0000000000..c075e586e6 --- /dev/null +++ b/working-with-files-in-python/tar_archives.py @@ -0,0 +1,89 @@ +import os +import shutil +import sys +import tarfile +import time +from pathlib import Path + +# Work inside a scratch folder with a few sample files to archive. +shutil.rmtree("tar_workspace", ignore_errors=True) +os.mkdir("tar_workspace") +os.chdir("tar_workspace") +for name in [ + "app.py", + "config.py", + "CONTRIBUTING.rst", + "CONTRIBUTORS.md", + "README.md", + "tests.py", + "foo.bar", +]: + Path(name).write_text(f"# {name}\n") + +with tarfile.open("example.tar", mode="w") as tar: + for name in ["CONTRIBUTING.rst", "README.md", "app.py"]: + tar.add(name) +for name in ["CONTRIBUTING.rst", "README.md"]: + os.remove(name) + +# Opening TAR archives +with tarfile.open("example.tar", "r") as tar_file: + print(tar_file.getnames()) + +tar = tarfile.open("example.tar", mode="r") +print(tar.getnames()) + +for entry in tar.getmembers(): + print(entry.name) + print(" Modified:", time.ctime(entry.mtime)) + print(" Size :", entry.size, "bytes") + print() + +# Extracting files from a TAR archive. Python 3.14 and later apply the +# "data" extraction filter by default. On 3.12 and 3.13, pass it yourself. +extract_options = {} if sys.version_info >= (3, 14) else {"filter": "data"} +tar.extract("README.md", **extract_options) +print(sorted(os.listdir("."))) +tar.extractall(path="extracted/", **extract_options) +print(sorted(os.listdir("extracted"))) + +f = tar.extractfile("app.py") +contents = f.read() +print(type(contents)) +tar.close() + +# Creating new TAR archives +file_list = ["app.py", "config.py", "CONTRIBUTORS.md", "tests.py"] +with tarfile.open("packages.tar", mode="w") as tar: + for file in file_list: + tar.add(file) + +# Read the contents of the newly created archive +with tarfile.open("packages.tar", mode="r") as t: + for member in t.getmembers(): + print(member.name) + +# Add a file to the existing archive +with tarfile.open("packages.tar", mode="a") as tar: + tar.add("foo.bar") + +with tarfile.open("packages.tar", mode="r") as tar: + for member in tar.getmembers(): + print(member.name) + +# Working with compressed archives +with tarfile.open("packages.tar.gz", mode="w:gz") as tar: + tar.add("app.py") + tar.add("config.py") + tar.add("tests.py") + +with tarfile.open("packages.tar.gz", mode="r:gz") as t: + for member in t.getmembers(): + print(member.name) + +# Zstandard compression requires Python 3.14 or later +if sys.version_info >= (3, 14): + with tarfile.open("packages.tar.zst", mode="w:zst") as tar: + tar.add("app.py") + with tarfile.open("packages.tar.zst", mode="r:zst") as t: + print(t.getnames()) diff --git a/working-with-files-in-python/temporary_files.py b/working-with-files-in-python/temporary_files.py new file mode 100644 index 0000000000..78d01fe87f --- /dev/null +++ b/working-with-files-in-python/temporary_files.py @@ -0,0 +1,29 @@ +import os +import tempfile +from tempfile import TemporaryFile + +# Create a temporary file and write some data to it +fp = TemporaryFile("w+t") +fp.write("Hello universe!") + +# Go back to the beginning and read data from file +fp.seek(0) +data = fp.read() +print(data) + +# Close the file, after which it will be removed +fp.close() + +with TemporaryFile("w+t") as fp: + fp.write("Hello universe!") + fp.seek(0) + print(fp.read()) +# File is now closed and removed + +with tempfile.TemporaryDirectory() as tmpdir: + print("Created temporary directory ", tmpdir) + print(os.path.exists(tmpdir)) + +# Directory contents have been removed +print(tmpdir) +print(os.path.exists(tmpdir)) diff --git a/working-with-files-in-python/traverse_directories.py b/working-with-files-in-python/traverse_directories.py new file mode 100644 index 0000000000..555edda940 --- /dev/null +++ b/working-with-files-in-python/traverse_directories.py @@ -0,0 +1,22 @@ +import os +from pathlib import Path + +os.chdir("walk_directory") + +print("--- os.walk(), top-down ---") +for dirpath, dirnames, files in os.walk("."): + print(f"Found directory: {dirpath}") + for file_name in files: + print(file_name) + +print("\n--- os.walk(), bottom-up ---") +for dirpath, dirnames, files in os.walk(".", topdown=False): + print(f"Found directory: {dirpath}") + for file_name in files: + print(file_name) + +print("\n--- Path.walk() ---") +for dirpath, dirnames, files in Path(".").walk(): + print(f"Found directory: {dirpath}") + for file_name in files: + print(dirpath / file_name) diff --git a/working-with-files-in-python/zip_archives.py b/working-with-files-in-python/zip_archives.py new file mode 100644 index 0000000000..fc26c0bcb4 --- /dev/null +++ b/working-with-files-in-python/zip_archives.py @@ -0,0 +1,61 @@ +import os +import shutil +import zipfile +from pathlib import Path + +# Work inside a scratch folder so that the extracted files don't mix with +# the scripts. The archive is built from the data/ folder that +# make_fixtures.py creates. +shutil.rmtree("zip_workspace", ignore_errors=True) +os.mkdir("zip_workspace") +shutil.make_archive("zip_workspace/data", "zip", "data/") +os.chdir("zip_workspace") + +# Reading ZIP files +with zipfile.ZipFile("data.zip", "r") as zipobj: + print(zipobj.namelist()) + +with zipfile.ZipFile("data.zip", "r") as zipobj: + bar_info = zipobj.getinfo("sub_dir/bar.py") + print(bar_info.file_size) + +print(bar_info.date_time) +print(bar_info.compress_size) +print(bar_info.filename) + +# Extracting ZIP archives +print(os.listdir(".")) +data_zip = zipfile.ZipFile("data.zip", "r") + +# Extract a single file to current directory +print(data_zip.extract("file1.py")) +print(os.listdir(".")) + +# Extract all files into a different directory +data_zip.extractall(path="extract_dir/") +print(os.listdir(".")) +print(os.listdir("extract_dir")) +data_zip.close() + +# Extracting data from password protected archives works like this, given +# an encrypted secret.zip. The password must be a bytes object: +# +# with zipfile.ZipFile("secret.zip", "r") as pwd_zip: +# pwd_zip.extractall(path="extract_dir", pwd=b"Quish3@o") + +# Creating new ZIP archives +os.chdir("extract_dir") +file_list = ["file1.py", "sub_dir/", "sub_dir/bar.py", "sub_dir/foo.py"] +with zipfile.ZipFile("new.zip", "w") as new_zip: + for name in file_list: + new_zip.write(name) + +# Open a ZipFile object in append mode +Path("data.txt").write_text("some data\n") +Path("latin.txt").write_text("Lorem ipsum dolor sit amet.\n") +with zipfile.ZipFile("new.zip", "a") as new_zip: + new_zip.write("data.txt") + new_zip.write("latin.txt") + +with zipfile.ZipFile("new.zip", "r") as new_zip: + print(new_zip.namelist()) From 47ca535070b597060e102363564a141eadceab0b Mon Sep 17 00:00:00 2001 From: Real Python Bot <42617967+realpython-bot@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:29:02 +0000 Subject: [PATCH 2/2] Shorten the get_files() print line to match the tutorial Co-Authored-By: Claude Opus 5.5 --- working-with-files-in-python/file_attributes.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/working-with-files-in-python/file_attributes.py b/working-with-files-in-python/file_attributes.py index eb8b7a08ef..e5db244928 100644 --- a/working-with-files-in-python/file_attributes.py +++ b/working-with-files-in-python/file_attributes.py @@ -15,9 +15,8 @@ def get_files(): for entry in dir_entries: if entry.is_file(): info = entry.stat() - print( - f"{entry.name}\t Last Modified: {convert_date(info.st_mtime)}" - ) + date = convert_date(info.st_mtime) + print(f"{entry.name}\t Last Modified: {date}") if __name__ == "__main__":