Python File Handling: Read, Write, Append, Delete Files

Python File Handling: Read, Write, Append, Delete Files

File handling is one of the most practical skills in Python programming. It allows your programs to interact with the computer’s storage — whether you’re saving logs, storing user data, reading configurations, or processing datasets. Without file handling, most real-world applications would not be possible.

💡 Tip: Think of file handling as “communication” between your Python code and your operating system.

Opening a File in Python

Python provides the built-in open() function to work with files. The general syntax is:

f = open("filename.txt", "mode")
  

File modes explained:

ModeDescription
"r"Read (default). Error if file doesn’t exist.
"w"Write. Creates a new file or overwrites existing content.
"a"Append. Adds content to the end of the file.
"x"Create. Fails if file already exists.
"t"Text mode (default).
"b"Binary mode (images, videos, etc.).

Reading Files

Use "r" mode to read an existing file. Python provides three methods:

MethodDescription
read()Reads the whole file as a single string.
readline()Reads one line at a time.
readlines()Reads all lines into a list.
f = open("example.txt", "r")
print(f.read())
f.close()
  

Writing to Files

Use "w" mode to create or overwrite a file:

f = open("example.txt", "w")
f.write("Hello, Python file handling!\n")
f.write("This file now has two lines.")
f.close()
  
⚠️ Warning: "w" mode erases any existing file content.

Appending to Files

Appending adds new content without removing existing data. Use "a" mode:

f = open("example.txt", "a")
f.write("\nThis new line is appended.")
f.close()
  

Deleting Files

Use the os module to delete files safely:

import os

if os.path.exists("example.txt"):
    os.remove("example.txt")
    print("File deleted successfully.")
else:
    print("The file does not exist.")
  

Using the with Statement

The with statement is recommended because it closes the file automatically:

with open("example.txt", "r") as f:
    data = f.read()
    print(data)
  
✅ Best Practice: Always use with for cleaner, safer file handling.

Real-World Uses of File Handling

  • Storing logs of applications
  • Saving user preferences and settings
  • Reading datasets (CSV, JSON)
  • Creating configuration files

Exercise

Try it yourself:

  1. Create a file students.txt and write 3 names.
  2. Append 2 more names.
  3. Read and print all names.
  4. Delete the file safely using os.remove().

FAQ

What’s the difference between "w" and "a" mode?

"w" overwrites the file, while "a" adds content to the end.

How do I handle binary files?

Use "rb" or "wb" mode for reading/writing binary files (e.g., images).

Can I open multiple files at once?

Yes, use multiple with open() statements or nested context managers.

Conclusion

Python file handling is a fundamental skill for any developer. By mastering read, write, append, and delete operations, you make your programs more powerful and practical. Keep practicing with small projects like loggers, note-taking apps, or dataset readers — they will sharpen your real-world coding skills.

📌Related Posts

Continue Learning: Explore more beginner-friendly topics and practice materials in our Programming Resource Hub.

Post a Comment

0 Comments