Python File Handling

Hey friends 👋 welcome back, In the last lesson, we learned about modules and libraries, Today, we are going to learn about file handling, which allows our programs to read from and write to files, File handling is important when you want to save information or work with existing data.

Opening a File

You can open a file using the open() function, Example:

file = open("example.txt", "w") # "w" means write mode file.write("Hello, welcome to Ridfortech!") file.close()
  • "w" mode creates a new file or overwrites an existing file

  • Always close the file after working with it

Reading from a File

You can read the contents of a file using read(), Example:

file = open("example.txt", "r") # "r" means read mode content = file.read() print(content) file.close()

Output:

Hello, welcome to Ridfortech!

Using with Statement

You can use the with statement to automatically close files, Example:

with open("example.txt", "r") as file: content = file.read() print(content)

Appending to a File

You can add content to an existing file using "a" mode, Example:

with open("example.txt", "a") as file: file.write("\nThis is an additional line.")

Practice Time

Create a Python file called file_handling.py and try these exercises, 1, Create a new file and write a welcome message, 2, Read the content of your file and print it, 3, Append another line to your file and print the updated content, 4, Use the with statement to read the file

Great job, You just learned how to read from and write to files in Python, In the next lesson, we will explore Python Error Handling, where we will learn how to handle mistakes in our programs using try, except, and finally, We will soon be launching our YouTube channel, where we are going to post step-by-step video tutorials on Python and other tech skills, These videos will make learning easier and more visual, helping beginners follow along confidently.