Python Basics — Day 12 File I/O in Python
Aspiring Full-Stack Developer | Python · Django · React · SQL | documenting my learning journey
Building skills in Python and full-stack development, with a focus on web apps and system design
Junior developer in training — Python, Django, React — preparing for a career in full-stack engineering
From Python basics to full-stack projects, sharing my progress as I grow into a developer
Future full-stack engineer | Learning in public: Python, APIs, Databases, and Web Development
01. Opening a File
f = open("test.txt", "w") # Open file
f.write("Hello File!") # Write content
f.close() # Close file
open("filename", "mode")"w": Write (overwrites existing content)"a": Append (add new content at the end)"r": Read
02. Writing to a File
f = open("example.txt", "w", encoding="utf-8")
f.write("First line\n")
f.write("Second line\n")
f.close()
👉 encoding="utf-8" prevents text (e.g., Korean) from breaking.
03. Reading from a File
Read Entire File
f = open("example.txt", "r", encoding="utf-8")
data = f.read()
print(data)
f.close()
Read Line by Line
f = open("example.txt", "r", encoding="utf-8")
line1 = f.readline()
line2 = f.readline()
print(line1, line2)
f.close()
Read All Lines as a List
f = open("example.txt", "r", encoding="utf-8")
lines = f.readlines()
for line in lines:
print(line.strip()) # Remove newline characters
f.close()
04. Using with (Recommended)
Files must always be closed after use.
Using with automatically closes the file.
with open("example.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
05. Writing a List to a File
fruits = ["Apple", "Banana", "Grape"]
with open("fruits.txt", "w", encoding="utf-8") as f:
for fruit in fruits:
f.write(fruit + "\n")
06. Reading Data and Processing
with open("fruits.txt", "r", encoding="utf-8") as f:
fruits = f.readlines()
fruits = [f.strip() for f in fruits] # Remove newlines
print(fruits) # ['Apple', 'Banana', 'Grape']
07. Practice Examples
Example 1: Simple Notepad (Write)
note = input("Enter your note: ")
with open("note.txt", "a", encoding="utf-8") as f:
f.write(note + "\n")
Example 2: Read Notes
with open("note.txt", "r", encoding="utf-8") as f:
print(f.read())