All Courses
Advanced Python

Python Files

File Modes

Mode Name Behaviour
"r" Read Opens existing file for reading (default)
"w" Write Creates a new file; overwrites if file already exists ⚠️
"a" Append Opens existing file; adds to the end without overwriting
"r+" Read + Write Opens existing file for both reading and writing

Opening & Closing a File

Manual open/close

file = open("file.txt", "r")
# ... file operations ...
file.close()   # always close — forgetting this can cause issues

⚠️ If an exception occurs before file.close(), the file stays open.

Preferred: with statement (context manager) ✅

with open("file.txt", "r") as file:
    # ... file operations ...
# file is automatically closed when the block ends — even if an exception occurs

File Paths

  • If the file is in the same directory as where you run the script, use just the filename: "file.txt"
  • If not, use the relative path from where the script is executed: "subfolder/file.txt"
  • Or use the absolute path: "C:/Users/Tim/documents/file.txt"

Python looks for files relative to the execution directory (where you run the script from), not necessarily where the .py file lives.


Reading Files

file.read() — entire file as one string

with open("file.txt", "r") as file:
    content = file.read()
    print(content)

file.readlines() — list of lines (each includes \n)

with open("file.txt", "r") as file:
    lines = file.readlines()
    print(lines)   # ['Hello world\n', 'Add line\n', '\n', ...]

file.read(n) — read exactly n characters

with open("file.txt", "r") as file:
    print(file.read(5))   # first 5 characters only

Guide: \n (newline) counts as 1 character.


Handling \n (Newline Characters)

Every time you press Enter in a file, a \n is inserted. These come along when you read lines.

Strip trailing whitespace/newlines

line = "Hello world\n"
print(line.strip())   # "Hello world" — removes leading/trailing whitespace and \n

Remove all newlines from a string

line = line.replace("\n", "")

Iterating Over a File

Loop line by line without loading the whole file into memory:

with open("file.txt", "r") as file:
    for line in file:
        print(line, end="")   # end="" prevents double newlines

Read only the first N lines

with open("file.txt", "r") as file:
    for i, line in enumerate(file):
        if i == 2:   # 0-indexed: stops after 3rd line
            break
        print(line, end="")

Writing Files ("w" mode)

with open("file2.txt", "w") as file:
    file.write("Hello world\n")
    file.write("This is line 2\n")
    file.write("This is line 3\n")
  • Creates the file if it doesn't exist
  • Completely overwrites the file if it already exists ⚠️
  • file.write() does not add newlines automatically — you must add \n yourself
  • Only accepts strings — convert numbers with str() before writing

Appending to Files ("a" mode)

with open("file.txt", "a") as file:
    file.write("\nNew line added")
  • Places cursor at the end of the file
  • Adds to the file without erasing existing content
  • Each run keeps adding more — careful with infinite growth

Read + Write ("r+" mode)

Opens for both reading and writing. Cursor starts at the beginning.

Common use case — read a value, update it

with open("score.txt", "r+") as file:
    score = file.read()           # read current value, cursor moves to end
    new_score = int(score) + 1
    file.seek(0)                  # move cursor back to beginning!
    file.write(str(new_score))    # overwrite with new value

⚠️ After reading, the cursor is at the end of the file. If you write without calling file.seek(0) first, you'll append instead of overwrite.


file.seek(position)

Moves the file cursor to a specific position:

Value Behaviour
file.seek(0) Move to beginning of file
file.seek(1) Set reference at current position
file.seek(2) Move to end of file

Most commonly used: seek(0) to reset to the beginning after reading.


Key Takeaways & Recap

Concept Summary
Always close files Use with statement to do this automatically
File path Relative to where you run the script, not where the .py file is
"w" mode Dangerous — silently overwrites existing files
\n in files Newlines are real characters; strip or replace them when processing text
file.write() Strings only; add \n manually; does not auto-format
file.seek(0) Required in "r+" mode before overwriting after a read
Iterating a file for line in file reads line by line without loading everything at once