Python File Handling Tutorial for Beginners
Python File Handling Tutorial for Beginners
Introduction
Have you ever wanted to save information using Python so that it stays available even after closing your program?
Python File Handling allows you to create files, write data, read information, and update existing files.
In this tutorial, we will learn how to create a text file and save simple information using easy Python examples.
1. What Is File Handling?
File handling means working with files through a programming language.
Using Python, we can:
Create a new file.
Write information into a file.
Read saved information.
Add new information to an existing file.
Close files safely.
2. Create Your First Text File
Let's create a file named student.txt and save some sample information.
file_name = "student.txt"
with open(file_name, "w", encoding="utf-8") as file:
file.write("Course=Python\n")
file.write("Level=Beginner\n")
file.write("Status=Learning\n")
print(f"{file_name} created successfully!")Output
student.txt created successfully!3. Understanding the Code
Step 1: Create a File Name
file_name = "student.txt"Here, file_name is a variable that stores the name of our text file.
Step 2: Open the File
with open(file_name, "w", encoding="utf-8") as file:Let's understand each part:
open()opens a file.file_namespecifies which file to open."w"means write mode.encoding="utf-8"specifies the text encoding.as filelets us work with the opened file using the variablefile.withautomatically closes the file when the block finishes.
Important: Write mode creates a file if it does not exist. If the file already exists, its previous content will be replaced.
Step 3: Write Information
file.write("Course=Python\n")
file.write("Level=Beginner\n")
file.write("Status=Learning\n")The write() method writes text into a file.
The \n character moves the next text to a new line.
Step 4: Display a Success Message
print(f"{file_name} created successfully!")This line displays a message in the terminal.
4. What Will the File Contain?
After running the program, student.txt will contain:
Course=Python
Level=Beginner
Status=LearningThe file is usually created in the program's current working directory.
5. How to Read a Text File
We can use Python to read the information saved in a file.
file_name = "student.txt"
with open(file_name, "r", encoding="utf-8") as file:
content = file.read()
print(content)Output
Course=Python
Level=Beginner
Status=LearningHere:
"r"means read mode.read()reads the entire file content.contentstores the text returned byread().print()displays the content.
6. Difference Between Write and Append Modes
Python provides different file modes for different purposes.
Write Mode ("w")
Write mode replaces the existing content with new content.
with open("student.txt", "w", encoding="utf-8") as file:
file.write("Topic=File Handling\n")After running this code, the previous content of student.txt will be replaced.
Append Mode ("a")
Append mode adds new content to the end of the existing file.
with open("student.txt", "a", encoding="utf-8") as file:
file.write("Practice=Daily\n")The new information is added without removing the existing content.
7. Why Use with open()?
The with open() statement automatically closes the file after the work is complete.
It makes file handling easier and helps prevent problems caused by leaving files open.
8. Common File Modes in Python
| Mode | Purpose |
|---|---|
"r" | Read an existing file |
"w" | Write and replace existing content |
"a" | Add content to the end of a file |
"x" | Create a new file; raise an error if it already exists |
"r+" | Read and write an existing file |
9. Practice Exercises
Try these exercises to improve your Python skills:
Create a file named
book.txt.Write a book title, author, and category into it.
Read the file and display its contents.
Add a new line using append mode.
Run the program again and observe the changes.
10. Conclusion
Python File Handling is an important skill for beginners. By learning open(), write(), read(), and file modes, you can start building programs that save and retrieve information.
Keep practising and gradually explore advanced topics such as exception handling, CSV files, and JSON files.
Happy Learning!
Comments
Post a Comment