- Core Definitions
- The
with open()Statement - Reading from Files
- Writing to Files
- The
osModule for Files - Quick Reference: File Modes
- Common Mistakes to Avoid
- File Path: A string that specifies the location of a file (e.g.,
'data/my_file.txt'or just'my_file.txt'if it's in the same directory). - File Object: The object that Python creates when you
open()a file. You use this object's methods (like.read()or.write()) to interact with the file. - File Mode: A character that tells Python how you want to open the file (
'r'for read,'w'for write,'a'for append).
This is the recommended way to work with files. It automatically handles closing the file, even if errors occur.
with open('my_file.txt', 'r') as file_object:
# Indented code that works with the file_object goes here.
contents = file_object.read()
# The file is automatically closed when the 'with' block is exited.
print(contents)Reads the entire content of the file into a single string. Best for small files.
with open('poem.txt', 'r') as file:
all_contents = file.read()This is the most common and memory-efficient way to read a file.
with open('data.txt', 'r') as file:
for line in file:
# .strip() removes leading/trailing whitespace, including the newline character
print(line.strip())When reading from a file, the print() function can be misleading. It automatically adds a newline character (\n) to the end of its output. This means that even if you use .strip() to remove the newline from the line you read, print() will add it right back.
Default Behavior:
for line in file:
# This prints each line on a new line because print() adds a newline
print(line.strip())How to Control It:
Use the end parameter in the print() function to change what character is added at the end.
for line in file:
# This will print all lines on the same line, separated by a space
print(line.strip(), end=' ')Reads the entire file into a list of strings, where each string is a line.
with open('data.txt', 'r') as file:
lines_list = file.readlines()
# lines_list is now ['First line\n', 'Second line\n', ...]Opens a file for writing. Creates the file if it doesn't exist. If it does exist, it ERASES all existing content.
# This will overwrite 'greetings.txt' or create it.
with open('greetings.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a new line.\n")Opens a file for appending. Creates the file if it doesn't exist. If it exists, it adds new content to the END of the file.
# This will add text to the end of 'greetings.txt' without erasing it.
with open('greetings.txt', 'a') as file:
file.write("Adding one more line.\n")You must import os before using these functions.
Checks if a file or directory exists at the given path. Returns True or False.
import os
if os.path.exists('my_data.txt'):
print("File found!")
else:
print("File not found.")Deletes a file. This will cause an error if the file doesn't exist.
import os
if os.path.exists('file_to_delete.txt'):
os.remove('file_to_delete.txt')
print("File deleted.")| Mode | Character | Description |
|---|---|---|
| Read | 'r' |
Opens a file for reading. Error if the file does not exist. (Default mode) |
| Write | 'w' |
Opens a file for writing. Creates a new file or erases an existing file. |
| Append | 'a' |
Opens a file for appending. Creates a new file or adds to the end of an existing file. |
| Read/Write | '+' |
Can be added to other modes (e.g., 'r+') to allow both reading and writing. |
❌ Forgetting the Newline Character (\n)
# Wrong: This will write "HelloWorld" on one line.
with open('test.txt', 'w') as f:
f.write("Hello")
f.write("World")✅ Add \n When You Want a New Line
# Correct
with open('test.txt', 'w') as f:
f.write("Hello\n")
f.write("World\n")❌ Assuming a File Exists
# Wrong: This will crash with a FileNotFoundError if 'scores.txt' doesn't exist.
with open('scores.txt', 'r') as f:
print(f.read())✅ Handle Potential Errors with try...except or os.path.exists()
# Correct (Option 1: try...except)
try:
with open('scores.txt', 'r') as f:
print(f.read())
except FileNotFoundError:
print("The scores file could not be found.")
# Correct (Option 2: os.path.exists)
import os
if os.path.exists('scores.txt'):
with open('scores.txt', 'r') as f:
print(f.read())
else:
print("The scores file could not be found.")Happy coding! 🐍✨