Python: Basics of File Handling

Introduction

Almost every program needs to work with files — whether it’s saving user data, reading configuration settings, or processing text. Python makes file handling simple and powerful. In this tutorial, we’ll explore how to open, read, write, and close files, along with best practices for safe file management.

 Previous Tutorial


Step 1: Opening a File    

Python uses the built-in open() function to work with files.

Code:

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

  • "example.txt" is the file name.
  • "r" means read mode.

 

Common modes:

  • "r" → Read (default)
  • "w" → Write (creates/overwrites file)
  • "a" → Append (adds to file)
  • "b" → Binary mode (e.g., images, PDFs)

 

Step 2: Reading Files

You can read the entire file or line by line.

Code:

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

content = file.read()

print(content)

print(len(content))

file.close()

 

Always close the file after use with file.close().

 




Reading line by line:

Code:

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

for line in file:

print(line.strip())

print(len(line.strip()))

file.close()


 

 

Step 3: Writing to Files

Use "w" mode to write (overwrites existing content).

Code:

file = open("example.txt", "w")

file.write("Hello, Python!\n")

file.write("This is a new line.")

file.close()


If the file doesn’t exist, Python creates it.


 


 Appending with "a" mode:

Code:

file = open("example.txt", "a")

file.write("\nAdding another line.")

file.close()

 


  

Step 4: Using with Statement (Best Practice)

Instead of manually closing files, use with. It automatically handles closing.

Code:

with open("example.txt", "r") as file:

    content = file.read()

    print(content)

This is the recommended way to handle files safely.


 


Step 5: Reading and Writing Together

You can combine reading and writing:

Code:

with open("example.txt", "r+") as file:

    content = file.read()

file.write("\nNew content added.")

 

  • "r+" allows both reading and writing.
  • File pointer starts at the beginning.


 


Step 6: Working with Binary Files

For non-text files (like images), use binary mode:

Code:

with open("eml_image.jpeg", "rb") as file:

    data = file.read()

    print(len(data))   # Prints size in bytes

Binary mode is essential for handling files beyond plain text.



 

Mini Exercise

Try this challenge:

  1. Create a new file called notes.txt.
  2. Write three lines of text into it.
  3. Reopen the file and read the content.
  4. Append one more line and print the final content.

 

Hint:

Code:

Step 1: Write

with open("notes.txt", "w") as file:

    file.write("Line 1\nLine 2\nLine 3\n")

 

Step 2: Read

with open("notes.txt", "r") as file:

    print(file.read())

 

Step 3: Append

with open("notes.txt", "a") as file:

    file.write("Line 4\n")

 

Step 4: Final Read

with open("notes.txt", "r") as file:

    print(file.read())

 

Conclusion

In this tutorial, you learned how to:

  • Open files in different modes (r, w, a, b)
  • Read and write text files
  • Use the with statement for safe handling
  • Work with binary files

 

File handling is a core skill for real-world applications. With it, you can build programs that store data, process logs, or manage documents.

In the next tutorial, we’ll explore error handling and exceptions — how to make your programs robust and prevent crashes.