File handling in Python

Posted by Daksh on Sunday, April 3, 2022

File handling in Python

Contents:

File path

Absolute path: The path that contains the root folder is called an absolute path. Example: C:\Users\Daksh\Blog\PythonPosts\demofile.txt

Relative path: The path that contains the current working directory is called a relative path. Example: ..\..\demofile.txt means that the file is two folders above the current working directory.

Open function

The open() function is used to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. It can READ, WRITE and CREATE a file.

The open() function takes two parameters; filename (or file location), and mode. Syntax open(<FILE_NAME> <FILE_LOCATION>, <MODE>)

file = open("demofile.txt", "r")
# read() function returns the entire content of the file as a string
# read(<INT_VALUE>) function returns the first <INT_VALUE> characters of the file as a string
# readline() function reads the first line of the file
# readline(<INT_VALUE>) function reads the first <INT_VALUE> characters of the first line of the file
# readlines() function reads all the lines of the file and returns a list of lines, therefore you can iterate through the list
content = file.readline()
print(content)
file.close()

The mode parameter is optional and the default value is ‘r’ which means open for reading in text mode. It also specifies whether you want the output to be in text or binary format.

There are four different methods (modes) for opening a file:

  • ‘r’ - Read - Default value. Opens a file for reading (in text format), error if the file does not exist
  • ‘rb’ - Read - Opens a file for reading (in binary format). The file pointer is placed at the beginning of the file.
  • ‘r+’ - Read and Write - Opens a file for both reading and writing (in text format).
  • ‘a’ - Append - Opens a file for appending, creates the file if it does not exist
  • ‘w’ - Write - Opens a file for writing, creates the file if it does not exist. If the file exists, it will overwrite the existing file.
  • ‘x’ - Create - Creates the specified file, returns an error if the file exists

Close function

The close() function is used to close an open file. It has no effect if the file is already closed. It is a good practice to use the close() function to close a file and free up the resources.

Another way to close a file is to use the with statement. This ensures that the file is closed when the block inside the with statement is exited. The with statement is better than using just open() function because it handles exceptions and errors, and closes the file automatically. Moreover, with statement returns a list of lines by default, so you don’t have to use readlines() function.

with open("demofile.txt", "r") as file:
    for line in file:
        print(line)
try:
    with open("createfile.txt", "w") as file:
    file.writelines([
        "You can create a multiline file using this method.\n",
        "Pass all the lines as a list to the writelines() function.\n",
        "You will need to add a newline character at the end of each line.\n",
        "If 'createfile.txt' already exists, it will overwrite the existing file.\n",
        "If you want to append to the file, use 'a' mode instead of 'w'.\n"
        ])
except FileNotFoundError as e:
    print("ERROR: ", e)

Text and Binary formats

Text format is user-friendly whereas binary format is machine-friendly and human unreadable. For better performance, it is recommended to use binary format. Text format is Python’s default format to read and write files. To use binary format, add ‘b’ to the mode parameter. Example: rb, wb, ab, rb+.