Python Basics: File Handling
Working with files is a crucial skill for Python programmers. Files help you store and access data even after your program ends. Let’s…
Python Basics: File Handling

Working with files is a crucial skill for Python programmers. Files help you store and access data even after your program ends. Let’s break down the basics: reading, writing, and handling files safely.
1. Opening a File
Use the open() function to work with files. Common modes are:
'r'— Read (default)'w'— Write (creates or overwrites)'a'— Append (adds to the end)
Example:
file = open("example.txt", "r") # open for reading
# Always remember to close when done!
file.close()
2. Reading From Files
To get file content, use read(), readline(), or a loop:
with open("hello.txt", "r") as f:
content = f.read()
print(content)
# 'with' handles closing the file automatically
Read line by line:
with open("hello.txt", "r") as f:
for line in f:
print(line.strip())
3. Writing to Files
Use 'w' (write) or 'a' (append):
with open("output.txt", "w") as f:
f.write("Hello, Python!\n")
with open("output.txt", "a") as f:
f.write("Another line.\n")
'w'replaces contents,'a'adds to the end.
4. File Handling and CSVs
Reading and writing CSV (comma-separated values) files is common in data work.
Example:
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["name", "age"])
writer.writerow(["Alex", "23"])with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
5. Handling Exceptions
Always catch errors to prevent crashes if a file isn’t found.
try:
with open("notfound.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found!")
Summary
- Use
open()and always close files (or usewith). - Read files with
read(),readline(), or line by line. - Write and append using modes
'w'and'a'. - Handle errors gracefully.
- Try reading/writing a CSV file for practice!
메타데이터
- post_id
- b09df62dad66
- slug
- python-basics-file-handling-b09df62dad66
- url
- https://python.plainenglish.io/python-basics-file-handling-b09df62dad66
- canonical_url
- https://python.plainenglish.io/python-basics-file-handling-b09df62dad66
- author_url
- https://medium.com/@gitanjalisoni
- status
- ok
- fetched_at
- 2026-08-17 09:51:46