1. Basic Operations

Quiz: 0/5

Imagine you have a notebook where you write down your notes. A file in a computer is just like that notebook—it stores information. File handling in Python is simply the way we create, open, read, write, and manage files using code.

For example, if you want to store your shopping list or save game progress, you’ll use file handling to do that.

Text vs. Binary Files

There are two main types of files:

  1. Text Files (.txt, .csv, .json, etc.)

    • These files store readable characters (letters, numbers, spaces, symbols).
    • You can open them in a text editor like Notepad or VS Code.
    • Example:
      Hello, world!
      This is a text file.
      
  2. Binary Files (.jpg, .mp3, .exe, etc.)

    • These files store data in binary format (0s and 1s).
    • You can’t read them directly because they store images, videos, or software code.
    • Example: A picture file is a binary file; you need an image viewer to see it.

File modes (r, w, a, rb, wb)

When working with files, we need to specify how we want to use them. Python provides different modes for opening files:

Mode Meaning
r Read mode (opens file for reading, error if file doesn’t exist)
w Write mode (creates a new file or overwrites an existing one)
a Append mode (adds data to an existing file without deleting its content)
rb Read binary mode (reads a file as binary, useful for images, videos)
wb Write binary mode (writes data in binary format, used for images, audio)

Opening, reading, writing, and closing files

Let’s see some basic operations:

Opening a file

file = open("example.txt", "r")  # Open a file in read mode

Reading a file

content = file.read()  # Read the entire file
print(content)
file.close()  # Always close the file!

Writing to a file

file = open("example.txt", "w")  # Open in write mode
file.write("Hello, this is a new file!")  # Write text to the file
file.close()  # Close the file

Appending to a file

file = open("example.txt", "a")  # Open in append mode
file.write("\nAdding a new line!")  # Appends new text
file.close()

Using binary mode

file = open("image.jpg", "rb")  # Open an image in binary read mode
data = file.read()
file.close()

Important notes

  • Always close the file after opening it using file.close().
  • Use with open(...) to automatically close the file:
    with open("example.txt", "r") as file:
        content = file.read()
        print(content)  # No need to manually close the file!
    

Conclusion

File handling is super useful for saving and reading data in programs.

  • Use text files for storing human-readable data (like notes, logs).
  • Use binary files for images, music, and other non-text content.
  • Choose the right mode (r, w, a, rb, wb) based on your needs.

Hands-On Practise

Exercise: Simple File Manager

Task

  1. Create a text file named my_notes.txt and write some text into it.
  2. Read the content of the file and print it.
  3. Append a new line to the file.
  4. Read the updated file again to see the changes.
Output:

Quizzes: 0/5

Question 1:

What is file handling in Python?

  • A way to manage files, including reading and writing data.
  • A function used to print file contents.
  • A library that stores Python files.
  • A method to delete files permanently.

Question 2:

Which file mode should you use to **only read** a file?

  • 'w' (write mode)
  • 'a' (append mode)
  • 'r' (read mode)
  • 'wb' (write binary mode)

Question 3:

What happens if you open a file in 'w' mode?

  • It appends data to the file.
  • It reads the file.
  • It deletes the existing content and starts a new file.
  • It raises an error if the file already exists.

Question 4:

Which mode should be used to **append** content to a file without deleting existing data?

  • 'r' (read mode)
  • 'a' (append mode)
  • 'w' (write mode)
  • 'rb' (read binary mode)

Question 5:

What is the difference between text files and binary files?

  • Text files store characters, while binary files store raw bytes.
  • Binary files contain only images, while text files contain only text.
  • Text files cannot be opened in Python.
  • There is no difference; they are the same.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Next lessonReading and writing files efficiently