Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

File Handling

What is File Handling?

File handling means your Python program can:

  • Create
  • Read
  • Write
  • Append
  • Delete

files like .txt, .csv, etc.

Why Use File Handling?

To save and access data permanently (outside the program), like:

  • Saving user input
  • Reading from configuration files
  • Logging information
  • Managing reports, etc.

Basic File Operations in Python

ModeMeaningDescription
'r'ReadOpens file for reading (default)
'w'WriteOverwrites file or creates new
'a'AppendAdds to the end of file
'x'CreateCreates file, error if exists
'rb'Read BinaryFor files like images, etc.

Basic Example: Read and Write

Writing to a file

file = open("demo.txt", "w")
file.write("Hello, this is Python file handling!")
file.close()

This creates a file demo.txt and writes a line inside it.

Reading from a file

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

Appending to a file

file = open("demo.txt", "a")
file.write("\nNew line added!")
file.close()

Delete a File

Use the os module to delete a file:

 import os

if os.path.exists("example.txt"):
    os.remove("example.txt")
else:
    print("File not found.")

Using with (Best Practice)

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

The with block automatically closes the file after use.

Summary

OperationFunction
Createopen("file.txt", "x")
Readopen("file.txt", "r")
Writeopen("file.txt", "w")
Appendopen("file.txt", "a")
Best wayUse with open(...) as ...:

    Leave a Reply

    Your email address will not be published.

    Need Help?