File Handling

File Handling

Python, like most programming languages, allows us to work with files directly from Python. Using Python we can read files stored in a file, as well as alter it, remove contents, or add more to it. We do not have to use any particular module to work with files. Python offers certain functions we can use to work with files.

To learn how to properly work with a file, let’s create a text file with the name ‘file_handling_contents.txt’. Copy this text given below and paste it to your text file and save it, alternatively feel free to use your custom text.

Hello!

Welcome everyone, this is a sample text I am using to illustrate the use of file handling in Python. We can open, alter and remove the contents of a file using File Handling in Python.

 

To open up a file in Python we can use the open() function, which is an in-built function in Python. The syntax is:

  • open(filename, mode)
    • filename – This would store the name of the file we are trying to access. In this blog, the file is stored in the same location as the Python file. If we want to access a file stored in another directory, we must provide the path or directory location of that file, followed by the filename as shown below:
      • Let’s say you want to view the contents of a file in a folder called “Documents” which is held in the “C” drive. So to access it we need to do the following:
      • "C:\Documents\file_handling_contents.txt"
  • mode – We have 4 different ways to work with a file and they are:
Serial No. Mode Description
1. r – Read Opens the specified file to read its contents and will return an error if the specified file does not exist. This is the default value.
2. w – Write Opens the specified file to write to it and in the case, the file does not exist it will create a file with the specified name in the directory (if provided).
3. a – Append Opens the specified file to append to it and in the case, the file does not exist it will create a file with the specified name in the directory (if provided).
4. x – Create Creates a file with the specified name and in the case, such a file exists it will return an error.

 

There are also two special modes we can use and they are:

Serial No. Mode Description
1. t – Text Opens a file in text mode. This is the default value.
2. b – Binary Opens a file in binary mode.

 

Take a look at the following example:

file_ = open("file_handling_contents.txt", "r")

for contents in file_:
    print(contents, end="")  # end specifies print to not add a newline after each line

file_.close()

When we run this code, we get:

We created a variable called “file_” which will hold the contents of the “file_handling_contents.txt” file. We used the “r” mode, so Python will only read the contents of the file. We used the for loop as we need to iterate through the items stored in the variable “file_”, and since our original text has one gap line, we specify the “end” parameter so Python does not print it with two gaps.

To get a better understanding of why we specified the end parameter try running the code with and without the end parameter, you’ll notice the difference instantaneously. Finally, we close our open file thus freeing up the resources we have taken

NOTE: In the above code snippet, the open() function can be written as:

file_ = open("file_handling_contents.txt")  # no mode specified
file_ = open("file_handling_contents.txt", "rt")  # default if mode not specified

We need to manually close the file that we open as there is a possibility of Python not closing the file or closing it after a much longer time. However, we can avoid this hassle and automate this by using the ‘with’ keyword. Using this automatically closes a file that we opened when we exit from the ‘with’ block. If we try to read from ‘file_’ after the ‘with’ block it raises the “ValueError” error.

with open("file_handling_contents.txt") as file_:
    data = file_.read()
    print(data)

This gives us the same output as before. We will cover reading, writing, and appending to a file in the next blog.

 

What have we learned?

  • How can we work with a text file using Python?
  • Which function can be used to access a file?
  • How do we access a file stored in another directory?
  • What are the 4 modes we have when opening a file in Python?
  • What are the 2 special modes we can use?
  • What are the default modes (when not specified) used in the open() function?
  • What advantage does the ‘with’ keyword offer when opening a file?
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments