File Handling in Python: Reading and Writing Files

December 11, 2023

Working with files is a common task in many programming projects. Whether you need to import data from an external source, export data for analysis, or simply store information for later use, knowing how to read from and write to files in Python is essential. In this lesson, we will cover the basics of file handling in Python, including different modes of file handling, error handling, and best practices.

Opening and Closing Files

In order to read from or write to a file in Python, we first need to open it. The open() function takes in two parameters: the name of the file we want to open, and the mode in which we want to open it. There are several modes available for file handling in Python:

  • r – read mode, used for reading from a file
  • w – write mode, used for writing to a file (overwrites existing content)
  • a – append mode, used for adding new content to the end of a file
  • r+ – read and write mode, used for both reading from and writing to a file

By default, the open() function will open a file in read mode if no mode is specified. It’s important to note that when we are done working with a file, we must close it using the close() method. This ensures that any changes we have made to the file are saved and that the file is available for other programs to use.

Reading from a File

Once we have opened a file, we can use the read() method to read the contents of the file. This method will return a string containing the entire contents of the file. For example:

file = open("data.txt", "r")
content = file.read()
print(content)
file.close()

In the code above, we open a file called data.txt in read mode and store the contents of the file in a variable called content. We then print the contents and close the file.

If we want to read only a certain number of characters from a file, we can use the read(n) method, where n is the number of characters we want to read. For example, file.read(10) will read the first 10 characters of the file.

Writing to a File

To write to a file in Python, we use the write() method. This method takes in a string as a parameter and writes it to the file. If we are using a mode other than w (write mode), the write() method will append the string to the end of the file. For example:

file = open("data.txt", "a")
file.write("This is a new line of text.")
file.close()

In the code above, we open the data.txt file in append mode and use the write() method to add a new line of text to the end of the file.

Error Handling

When working with files, it’s important to handle any potential errors that may occur. One common error is the FileNotFoundError, which occurs when the file we are trying to open does not exist. To handle this error, we can use a try/except block:

try:
  file = open("data.txt", "r")
  content = file.read()
  print(content)
  file.close()
except FileNotFoundError:
  print("File not found.")

In the code above, we attempt to open the data.txt file in read mode. If the file does not exist, the except block will run and print an error message.

Best Practices

When working with files in Python, there are a few best practices to keep in mind:

  • Always close a file after you are done working with it.
  • Use the with statement to automatically close a file when you are done with it.
  • Always handle potential errors when working with files.
  • Use descriptive variable names when working with files to make your code more readable.

By following these best practices, you can ensure that your file handling code is efficient, readable, and error-free.

Conclusion

In this lesson, we covered the basics of file handling in Python, including different modes of file handling, error handling, and best practices. Now that you have a solid understanding of how to read from and write to files in Python, you can use this knowledge in your future programming projects.