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
57 changes: 57 additions & 0 deletions read-write-files-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Reading and Writing Files in Python

This folder provides the code examples for the Real Python tutorial [Reading and Writing Files in Python (Guide)](https://realpython.com/read-write-files-python/).

## Setup

The examples only use Python's standard library, so there's nothing to install. You need Python 3.6 or later. On Python 3.14 and older, the default text encoding depends on your operating system's locale, so the output of some examples may differ on Windows.

## Usage

The scripts read and write their files in the current working directory, so run them from inside this folder:

```shell
$ python reading_files.py
```

Each script holds the code from one section of the tutorial. The examples that the tutorial shows at the interactive prompt are included as `print()` calls, in the same order as the article:

| File | Tutorial section |
| --- | --- |
| `character_encodings.py` | Character Encodings |
| `file_objects.py` | Opening and Closing a File in Python |
| `reading_files.py` | Reading and Writing Opened Files, Iterating Over Each Line in the File |
| `writing_files.py` | Reading and Writing Opened Files (writing) |
| `working_with_bytes.py` | Working With Bytes |
| `create_dos_file.py`, `dos2unix.py`, `compare_line_endings.py` | A Full Example: `dos2unix.py` |
| `project/` | Locating Your Script With `__file__` |
| `appending.py` | Appending to a File |
| `two_files.py` | Working With Two Files at the Same Time |
| `pathlib_read_write.py` | Reading and Writing Files With `pathlib` |
| `my_file_reader.py`, `png_reader.py`, `read_png_chunks.py` | Creating Your Own Context Manager |

To try the `dos2unix` tool, create a file with Windows line endings first, convert it, and then compare the raw bytes:

```shell
$ python create_dos_file.py
$ python dos2unix.py dog_breeds_dos.txt
$ python compare_line_endings.py
```

To see `__file__` in action, run `main.py` from the `project/` folder:

```shell
$ cd project/
$ python main.py
```

There are also two data files:

| File | Description |
| --- | --- |
| `dog_breeds.txt` | The ten dog breeds that the tutorial reads and writes |
| `jack_russell.png` | The Jack Russell Terrier picture from the tutorial, used by the binary examples |

`appending.py` adds `Beagle` to `dog_breeds.txt`, just like the tutorial does before the `pathlib` section. Restore the file afterward if you want to run the other examples again with the original ten breeds. The other scripts create new files such as `dog_breeds_reversed.txt` and `dog_breeds_copy.txt`, which aren't checked in.

The photo of the Jack Russell Terrier is from [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Jack_Russell_Terrier_1.jpg) and is licensed under [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/).
5 changes: 5 additions & 0 deletions read-write-files-python/appending.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
with open("dog_breeds.txt", "a") as a_writer:
a_writer.write("Beagle\n")

with open("dog_breeds.txt", "r") as reader:
print(reader.read())
8 changes: 8 additions & 0 deletions read-write-files-python/character_encodings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
with open("greeting.txt", "w", encoding="utf-8") as writer:
print(writer.write("Grüße!\n"))

try:
with open("greeting.txt", encoding="ascii") as reader:
reader.read()
except UnicodeDecodeError as error:
print(f"UnicodeDecodeError: {error}")
5 changes: 5 additions & 0 deletions read-write-files-python/compare_line_endings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
with open("dog_breeds_dos.txt", "rb") as reader:
print(reader.read())

with open("dog_breeds_dos_unix.txt", "rb") as reader:
print(reader.read())
2 changes: 2 additions & 0 deletions read-write-files-python/create_dos_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
with open("dog_breeds_dos.txt", "w", newline="\r\n") as writer:
print(writer.write("Pug\nJack Russell Terrier\n"))
10 changes: 10 additions & 0 deletions read-write-files-python/dog_breeds.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Pug
Jack Russell Terrier
English Springer Spaniel
German Shepherd
Staffordshire Bull Terrier
Cavalier King Charles Spaniel
Golden Retriever
West Highland White Terrier
Boxer
Border Terrier
87 changes: 87 additions & 0 deletions read-write-files-python/dos2unix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""
A simple script and library to convert files or strings from DOS-like
line endings to Unix-like line endings.
"""

import argparse
import os


def str2unix(input_str: str) -> str:
r"""
Converts the string from \r\n line endings to \n

Parameters
----------
input_str
The string whose line endings will be converted

Returns
-------
The converted string
"""
r_str = input_str.replace("\r\n", "\n")
return r_str


def dos2unix(source_file: str, dest_file: str):
"""
Converts a file that contains DOS-like line endings into Unix-like

Parameters
----------
source_file
The path to the source file to be converted
dest_file
The path to the converted file for output
"""
# NOTE: Could add file existence checking and file overwriting
# protection
with open(source_file, "r", encoding="utf-8", newline="") as reader:
dos_content = reader.read()

unix_content = str2unix(dos_content)

with open(dest_file, "w", encoding="utf-8", newline="") as writer:
writer.write(unix_content)


if __name__ == "__main__":
# Create the argument parser and set its description
parser = argparse.ArgumentParser(
description="Convert a DOS-like file to a Unix-like file",
)

# Add the arguments:
# - source_file: the source file we want to convert
# - dest_file: the destination where the output should go

# Note: the use of the argument type of argparse.FileType could
# streamline some things
parser.add_argument(
"source_file",
help="The location of the source file",
)

parser.add_argument(
"--dest_file",
help=(
"Location of the destination file "
"(default: source_file appended with `_unix`)"
),
default=None,
)

# Parse the args (argparse automatically grabs the values from sys.argv)
args = parser.parse_args()

s_file = args.source_file
d_file = args.dest_file

# If the destination file wasn't passed, then assume we want to
# create a new file based on the old one
if d_file is None:
file_path, file_extension = os.path.splitext(s_file)
d_file = f"{file_path}_unix{file_extension}"

dos2unix(s_file, d_file)
15 changes: 15 additions & 0 deletions read-write-files-python/file_objects.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
with open("dog_breeds.txt") as file:
print(type(file))

with open("dog_breeds.txt", "rb") as file:
print(type(file))

# Opening dog_breeds.txt in "wb" mode would truncate it, so use a new file
with open("dog_breeds_copy.txt", "wb") as file:
print(type(file))

with open("dog_breeds.txt", "rb", buffering=0) as file:
print(type(file))

with open("dog_breeds.txt", "r", encoding="utf-8") as reader:
print(reader.readline(), end="")
Binary file added read-write-files-python/jack_russell.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 19 additions & 0 deletions read-write-files-python/my_file_reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class MyFileReader:
def __init__(self, file_path):
self.__path = file_path
self.__file_object = None

def __enter__(self):
self.__file_object = open(self.__path)
return self

def __exit__(self, exc_type, exc_value, exc_tb):
self.__file_object.close()

# Additional methods implemented below


if __name__ == "__main__":
with MyFileReader("dog_breeds.txt") as reader:
# Perform custom class operations
pass
6 changes: 6 additions & 0 deletions read-write-files-python/pathlib_read_write.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from pathlib import Path

path = Path("dog_breeds.txt")
content = path.read_text(encoding="utf-8")
print(content.splitlines()[:3])
print(Path("dog_breeds_copy.txt").write_text(content, encoding="utf-8"))
44 changes: 44 additions & 0 deletions read-write-files-python/png_reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class PngReader:
# Every .png file contains this in the header. Use it to verify
# the file is indeed a .png.
_expected_magic = b"\x89PNG\r\n\x1a\n"

def __init__(self, file_path):
# Ensure the file has the right extension
if not file_path.endswith(".png"):
raise ValueError("File must have a '.png' extension")
self.__path = file_path
self.__file_object = None

def __enter__(self):
self.__file_object = open(self.__path, "rb")

magic = self.__file_object.read(8)
if magic != self._expected_magic:
raise ValueError("The file is not a properly formatted .png file!")

return self

def __exit__(self, exc_type, exc_value, exc_tb):
self.__file_object.close()

def __iter__(self):
# This and __next__() are used to create a custom iterator
return self

def __next__(self):
# Read the file in "chunks", the building blocks of a PNG
initial_data = self.__file_object.read(4)

# The file has reached EOF. This means we can't go any further,
# so stop the iteration by raising StopIteration.
if initial_data == b"":
raise StopIteration
else:
# Each chunk has a len, type, data (based on len) and crc
# Grab these values and return them as a tuple
chunk_len = int.from_bytes(initial_data, byteorder="big")
chunk_type = self.__file_object.read(4)
chunk_data = self.__file_object.read(chunk_len)
chunk_crc = self.__file_object.read(4)
return chunk_len, chunk_type, chunk_data, chunk_crc
6 changes: 6 additions & 0 deletions read-write-files-python/project/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Importing the test modules runs them, so the imports are intentional
# ruff: noqa: F401
import tests.test_commanding
import tests.test_power
import tests.test_wire_housing
import tests.test_leds
3 changes: 3 additions & 0 deletions read-write-files-python/project/tests/test_commanding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
print(f"{__file__} Started:")
# Run the actual test here...
print(f"{__file__} Passed!")
3 changes: 3 additions & 0 deletions read-write-files-python/project/tests/test_leds.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
print(f"{__file__} Started:")
# Run the actual test here...
print(f"{__file__} Passed!")
3 changes: 3 additions & 0 deletions read-write-files-python/project/tests/test_power.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
print(f"{__file__} Started:")
# Run the actual test here...
print(f"{__file__} Passed!")
3 changes: 3 additions & 0 deletions read-write-files-python/project/tests/test_wire_housing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
print(f"{__file__} Started:")
# Run the actual test here...
print(f"{__file__} Failed!")
5 changes: 5 additions & 0 deletions read-write-files-python/read_png_chunks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from png_reader import PngReader

with PngReader("jack_russell.png") as reader:
for length, kind, data, crc in reader:
print(f"{length:05}, {kind}, {crc}")
39 changes: 39 additions & 0 deletions read-write-files-python/reading_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
with open("dog_breeds.txt", "r") as reader:
# Read & print the entire file
print(reader.read())

with open("dog_breeds.txt", "r") as reader:
# Read & print the first 5 characters of the line 5 times
print(reader.readline(5))
# Notice that line is greater than the 5 chars and continues
# down the line, reading 5 chars each time until the end of the
# line and then "wraps" around
print(reader.readline(5))
print(reader.readline(5))
print(reader.readline(5))
print(reader.readline(5))

with open("dog_breeds.txt") as reader:
print(reader.readlines()) # Returns a list object

with open("dog_breeds.txt") as reader:
print(list(reader))

print("\n--- Iterating with .readline() ---")
with open("dog_breeds.txt", "r") as reader:
# Read and print the entire file line by line
line = reader.readline()
while line != "": # The EOF char is an empty string
print(line, end="")
line = reader.readline()

print("\n--- Iterating with .readlines() ---")
with open("dog_breeds.txt", "r") as reader:
for line in reader.readlines():
print(line, end="")

print("\n--- Iterating over the file object ---")
with open("dog_breeds.txt", "r") as reader:
# Read and print the entire file line by line
for line in reader:
print(line, end="")
5 changes: 5 additions & 0 deletions read-write-files-python/two_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
d_path = "dog_breeds.txt"
d_r_path = "dog_breeds_reversed.txt"
with open(d_path, "r") as reader, open(d_r_path, "w") as writer:
dog_breeds = reader.readlines()
writer.writelines(reversed(dog_breeds))
9 changes: 9 additions & 0 deletions read-write-files-python/working_with_bytes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
with open("dog_breeds.txt", "rb") as reader:
print(reader.readline())

with open("jack_russell.png", "rb") as byte_reader:
print(byte_reader.read(1))
print(byte_reader.read(3))
print(byte_reader.read(2))
print(byte_reader.read(1))
print(byte_reader.read(1))
13 changes: 13 additions & 0 deletions read-write-files-python/writing_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
with open("dog_breeds.txt", "r") as reader:
# Note: readlines doesn't trim the line endings
dog_breeds = reader.readlines()

with open("dog_breeds_reversed.txt", "w") as writer:
# Alternatively, you could use writer.writelines(reversed(dog_breeds))

# Write the dog breeds to the file in reversed order
for breed in reversed(dog_breeds):
writer.write(breed)

with open("dog_breeds_reversed.txt", "r") as reader:
print(reader.read())
Loading