Learn › Linux Systems Programming with Python › Files, bytes and file descriptors
Open a file, inspect its descriptor, write and read UTF-8 text, and change a program to preserve existing content.
Why can a one-line Python program erase yesterday’s notes before it writes a single character? The mode you give open() tells Linux what to do with the existing file. You’ll see the difference, change a program to keep the old line, and verify exactly which bytes it wrote.
You should know how to run a Python script, use strings and variables, and navigate directories in a Linux terminal. Open the workspace editor and use its terminal, so the script you save is the one Python runs. pwd shows the terminal’s current directory. Use cd /home/admin in the lesson terminal if it opened elsewhere. A filename such as example.txt with no directory prefix is relative to that directory. Work only with the exercise files here.
When you run python3, Linux starts a process, a running instance of the Python interpreter. For a call such as open("example.txt", "w", encoding="utf-8"), Python asks Linux to open that path for writing. Once Linux opens the file, it gives the process a file descriptor, a small number it can use to refer to that open file. Python wraps the descriptor in a file object, which gives your code methods such as .write() and .read(). The descriptor belongs to this process while it’s open. Linux can reuse the same number after closing it.
| Mode | What opening the file does |
|---|---|
"r" | Opens an existing file for reading as text. A missing file raises FileNotFoundError. |
"rb" | Opens an existing file for reading as bytes, with no decoding. |
"w" | Opens for writing as text. Creates a missing file or empties an existing one at open time. |
"a" | Opens for appending text. Keeps existing contents, puts writes at the end and creates the file if it’s missing. |
Save this as file_example.py in the workspace. with keeps the file open for the indented block and closes it when the block ends, even if the block raises an exception. The variable still exists after the block, so you can inspect .closed.
import os
text = "café\n"
with open("example.txt", "w", encoding="utf-8") as writer:
fd = writer.fileno()
print("Descriptor:", fd)
print("Linux link:", os.readlink(f"/proc/self/fd/{fd}"))
print("Open inside block:", not writer.closed)
print("Characters written:", writer.write(text))
print("Closed after block:", writer.closed)
with open("example.txt", "r", encoding="utf-8") as reader:
print("Text:", repr(reader.read()))
with open("example.txt", "rb") as reader:
raw = reader.read()
print("Bytes:", raw)
print("Byte count:", len(raw))
Run the saved file in the terminal.
python3 file_example.py
This authored example shows the expected output. 3 is an example descriptor. Use the number you see from your own run.
Descriptor: 3
Linux link: /home/admin/example.txt
Open inside block: True
Characters written: 5
Closed after block: True
Text: 'café\n'
Bytes: b'caf\xc3\xa9\n'
Byte count: 6
The descriptor number comes from writer.fileno(). Linux shows the open descriptors for the current process under /proc/self/fd. os.readlink() reads the target of the entry named by fd, so you can match the number to example.txt while the file is open. Closing the file releases that descriptor. A separate read after the close checks the content available to another reader.
The mode is "w" because this script can replace its own example.txt each time. The file holds bytes. With encoding="utf-8", Python turns a str into UTF-8 bytes when it writes and changes those bytes back into a str when it reads. repr() displays the newline as \n so you can see it. c, a, f and the newline take one byte each. é takes the two bytes c3 a9, which explains why the five characters use six bytes.
Create a separate practice file with one line. The > in this terminal command writes only to rehearsal.txt and replaces its contents if it exists.
printf 'first\n' > rehearsal.txt
In the editor, save a second script as rehearse_append.py.
with open("rehearsal.txt", "a", encoding="utf-8") as writer:
writer.write("second\n")
with open("rehearsal.txt", "r", encoding="utf-8") as reader:
print(repr(reader.read()))
python3 rehearse_append.py
Compare your result with 'first\nsecond\n'. "a" keeps first and writes second after its newline. Run the script once more without seeding the file again. Look for a second copy of the second line and explain where it came from. To replay, rerun the printf command first. If you’re unsure how the mode and newline work together, replay this practice or the worked example before continuing. Help and uncertainty carry no penalty.
Open the provided write_note.py in the editor. On the first attempt, it opens note.txt in "w" mode and writes "café\n". If you’ve already made the fix and want to replay the prediction, first save a copy of your working script, then change the mode in write_note.py back to "w" and save. Seed note.txt with its starting line and inspect it before running the program.
printf 'seed\n' > note.txt
cat note.txt
Before you run the program, write down whether seed will still be there, and why the mode matters. You can write unsure and continue. Then inspect your actual terminal results.
python3 write_note.py
cat note.txt
od -An -t x1 note.txt
od prints the file one byte at a time as two-digit hexadecimal values. -An hides the byte positions. Compare the lines and bytes you saw after the run with the starting line. If only café remains, opening in "w" emptied the file and the program wrote a new line. The bytes c3 a9 identify the UTF-8 encoding of é, and 0a is the newline. If both lines remain, inspect the saved mode and use pwd to check that you’re running the script you opened. If python3 reports an error, read it before interpreting any file contents.
The goal is to add the new line without erasing the existing one. Choose a mode that keeps existing bytes and writes at the end, then change and save write_note.py. Keep the explicit UTF-8 encoding and the newline in "café\n". If you need a hint, compare the modes table with the worked rehearsal.
The first run changed note.txt. Restore the known starting line for this exercise before testing your edit.
printf 'seed\n' > note.txt
python3 write_note.py
cat note.txt
od -An -t x1 note.txt
Check for seed followed by café on the next line. Compare the hexadecimal bytes with 73 65 65 64 0a 63 61 66 c3 a9 0a. The first five bytes are the original line including its newline. The next six bytes are the UTF-8 text and newline you appended. This confirms the contents a new reader sees after your program exits.
Use Check chapter for automatic feedback. Your own explanation should connect the mode to what happened to the original line, and connect the encoding to the byte count.
In a later practice session, make a copy of your script that writes to a different file in the same workspace. Begin with a file that contains first with no newline at the end. Your goal is exactly two separate lines, first and café, each ending in a newline. Try to explain what a plain append would do before running anything. Then inspect the bytes, choose a change and verify the two lines. Repeat the test with a starting file that already ends in a newline. Explain how you avoided joining the lines in the first case or adding a blank line in the second.
Practice What happens when Python opens a file? in a real Linux terminal at The Linux Camp. Progress is verified automatically as you type commands on the machine.