Python File Handling Tutorial (Beginner
to Practical)
1. What is File Handling?
File handling means reading from and writing to files stored on your computer.
It allows programs to save data permanently instead of losing it after execution.
2. Opening a File
file = open('[Link]', 'mode')
Modes:
r - read
w - write (overwrite)
a - append
x - create new file
3. Writing to a File
file = open('[Link]', 'w')
[Link]('Hello, this is my first file!\n')
[Link]('I am learning Python file handling.')
[Link]()
Explanation:
- 'w' creates or overwrites file
- \n creates a new line
- close() saves changes
4. Reading from a File
file = open('[Link]', 'r')
content = [Link]()
print(content)
[Link]()
5. Reading Line by Line
file = open('[Link]', 'r')
for line in file:
print(line)
[Link]()
6. Appending to a File
file = open('[Link]', 'a')
[Link]('\nThis line is added later.')
[Link]()
7. Best Practice (Using with)
with open('[Link]', 'w') as file:
[Link]('Safe and clean code!')
Automatically closes file and prevents errors.
8. Save User Input to File
name = input('Enter your name: ')
age = input('Enter your age: ')
with open('[Link]', 'a') as file:
[Link]('Name: ' + name + ', Age: ' + age + '\n')
print('Data saved successfully!')
9. Read Saved Data
with open('[Link]', 'r') as file:
for line in file:
print(line)
10. Simple Login System
# Register
username = input('Create username: ')
password = input('Create password: ')
with open('[Link]', 'a') as file:
[Link](username + ',' + password + '\n')
# Login
user = input('Enter username: ')
pwd = input('Enter password: ')
found = False
with open('[Link]', 'r') as file:
for line in file:
u, p = [Link]().split(',')
if user == u and pwd == p:
found = True
break
if found:
print('Login successful!')
else:
print('Invalid credentials!')
11. Common Mistakes
- Forgetting to close file
- Using 'w' which overwrites data
- Trying to read a file that does not exist