17. File Handling

Quiz: 0/5

Imagine storing information like your favorite recipes, a journal, or even game scores in a file. Python makes it simple to work with files so you can save data for later use or read data from existing files.

Opening and closing files in Python

To work with a file, you need to open it first. Python provides the open() function to do this.

Example:

file = open("example.txt", "r")  # Opens a file in read mode
file.close()  # Always close a file after using it

Modes for opening files:

  • r: Read (default)
  • w: Write (overwrites the file or creates it if it doesn't exist)
  • a: Append (adds to the file without overwriting)

Reading from a file

You can read the contents of a file using the read() method.

Example:

file = open("example.txt", "r")
content = file.read()
print(content)  # Displays the content of the file
file.close()

Writing to a file

To add text to a file, use the write() method. Be careful: writing will erase the file's previous content.

Example:

file = open("example.txt", "w")
file.write("Hello, Python!")  # Writes text to the file
file.close()

Safely handling files with with

Using with ensures the file is closed automatically, even if something goes wrong.

Example:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)  # The file is automatically closed after this block

Key takeaways

  • Always close your files or use the with statement.
  • Use the correct file mode (r, w, a) depending on your task.
  • Reading and writing files is simple but powerful for real-world applications.

Hands-On Practise

Exercise: Simple Log Writer and Reader

Task

  1. Create a Python script that writes a series of predefined messages to a file called log.txt.
    • Each message should include a timestamp (e.g., 2025-01-15: Starting process...).
    • Write at least three different messages.
  2. After writing the messages, the script should read the content of log.txt and display it.

Hints

  • Use the datetime module to include timestamps.
  • Use the w mode to create or overwrite the file.
  • Use the with statement for both writing and reading.
Output:

Quizzes: 0/5

Question 1:

What is the purpose of the 'with' statement in Python file handling?

  • To open multiple files simultaneously.
  • To automatically close the file after the block is executed.
  • To specify the file mode for reading or writing.
  • To handle file errors during execution.

Question 2:

Which mode is used to append data to an existing file?

  • 'r'
  • 'w'
  • 'a'
  • 'x'

Question 3:

What will happen if you try to read a non-existent file using 'open()' with mode 'r'?

  • The file will be created automatically.
  • An empty file will be opened.
  • An error will occur.
  • The program will skip the file.

Question 4:

Which method is used to read the entire content of a file as a single string?

  • readline()
  • readlines()
  • read()
  • write()

Question 5:

What is the result of using 'w' mode on an existing file?

  • The file is opened for reading only.
  • The file is appended to without overwriting.
  • The file is overwritten, and previous data is lost.
  • An error is raised because the file already exists.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonFiltering and transforming Data with List ComprehensionsNext lessonIntroduction to Python Functions