File Handling

File handling in Python is the process of working with files, including reading from files, writing to files, and performing various operations on files. Python provides built-in functions and methods for handling files.

  • Before you can perform any file operations, you need to open the file using the open() function.
  • When you're done with a file, it's important to close it using the close() method to free up system resources.

Modes for Opening Files

The second mode in the open() function specifies the mode in which the file is opened.

  • Read("r") opens file for reading
  • Write("w") opens file for writing
  • Append("a") opens the file for writing but appends new data to the end of the file. If the file doesn't exist, it creates a new file.
  • Exclusive creation("x") creates a new file and opens it for writing.
  • Binary Mode("b") opens the file in binary mode, which is used for non-text files
  • Text Mode("t") opens the file in text mode

Reading from Files

The contents of a file can be read using different methods;

Writing to Files

You can write data to a file using methods like write().

Appending to Files

To append data to an existing file, use the "a" mode.

Using with Statements

A better practice is to use the with statement (context manager), which ensures that the file is properly closed even if an exception occurs.

File Iteration

You can iterate through the lines of a file using a for loop.

Exception Handling for File Operations

File operations may raise exceptions, such as FileNotFoundError when attempting to open a non-existent file or PermissionError when attempting to write to a read-only file. Always include proper exception handling when working with files.

Deleting Files

To delete a file, you can use the os.remove() function from the os module.

Renaming and Moving Files

You can use the os.rename() function to rename files or move them to a different directory.

Working with Directories

The os module also provides functions for creating, listing, and deleting directories.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min