Day 6: File Handling in Python – Python 30-Day Challenge ??
Welcome to Day 6 of my Python learning journey! Today, I explored File Handling in Python, an essential skill for reading, writing, and managing files. Whether you're handling logs, user data, or configuration files, knowing how to work with files is a fundamental part of programming.
?? What I Learned Today
?? File Handling in Python
Python makes file operations easy and efficient using built-in functions. The key operations include:
? Reading files (r mode) ? Writing to files (w mode) ? Appending to files (a mode) ? Reading & Writing binary files (rb, wb modes)
?? Opening a File
The open() function is used to open a file.
file = open("example.txt", "r") # Open file in read mode
content = file.read() # Read the entire file
print(content)
file.close() # Always close the file after reading
?? Using with statement (Best practice: no need to manually close the file)
with open("example.txt", "r") as file:
content = file.read()
print(content) # File closes automatically after block execution
?? Writing to a File
We can write to a file using write (w) mode, which overwrites existing content.
with open("example.txt", "w") as file:
file.write("Hello, Python!")
?? Appending to a File (a mode) Use a mode to add content instead of overwriting.
with open("example.txt", "a") as file:
file.write("\nAppending this line!")
?? Reading Files: Different Methods
?? Read File Line by Line
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # Removes extra newline characters
领英推荐
?? Read Specific Number of Characters
with open("example.txt", "r") as file:
print(file.read(10)) # Reads first 10 characters
?? Read File as a List of Lines
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines) # Output: ['Hello, Python!\n', 'Appending this line!']
?? Writing Lists to a File
We can write multiple lines using writelines().
names = ["Alice\n", "Bob\n", "Charlie\n"]
with open("names.txt", "w") as file:
file.writelines(names)
?? Exercise: Putting It into Practice
? 1. Read a Text File and Print Its Content
with open("sample.txt", "r") as file:
print(file.read())
? 2. Write a List of Names to a File
names = ["Alice", "Bob", "Charlie"]
with open("names.txt", "w") as file:
for name in names:
file.write(name + "\n")
?? Resources Used
Final Thoughts
File handling is crucial for working with real-world applications, such as storing user data, logs, and reports. Learning these concepts makes Python programming even more powerful!
?? Next up: Error Handling & Exceptions! Excited to keep learning. Drop a comment if you have any questions or feedback! ??
#Python #Day6 #30DayChallenge #Learning #Coding #Programming #PythonForBeginners