File Handling in Python

File handling allows Python programs to read data from files and write data to files. It is useful for storing data permanently.

💡 Files are used to save data even after the program ends.

Opening a File

Use the open() function to open a file.

file = open("data.txt", "r")

Common file modes:

  • "r" – Read
  • "w" – Write
  • "a" – Append
  • "x" – Create

Reading a File

file = open("data.txt", "r")
content = file.read()
print(content)
file.close()

Writing to a File

file = open("data.txt", "w")
file.write("Hello Python!")
file.close()
❗ Using "w" mode will overwrite existing content.

Appending to a File

file = open("data.txt", "a")
file.write("\nWelcome to Python Learning")
file.close()

Using with Statement

The with statement automatically closes the file.

with open("data.txt", "r") as file:
    print(file.read())

Practice Exercises

  1. Create a file and write your name into it
  2. Read the file content
  3. Append your city to the same file