Python File Handling Methods |Operations on Files in Python

This article focuses on working with files (input / output) in Python : opening, reading, writing, closing and other operations. A file is just a collection of data stored as a sequence of bits on a computer. The information is stored in a heap of data (data structure) and is named “filename”. There are two main types of files utilized in Python: text file & binary file

Most used type of Files in Python

Below are some general type of file that we usually interact in python programs.

Text Files

These are files with human readable content. They store sequences of characters that a person understands. Notepad and other standard editors can read and edit this type of file. Text can be stored in two formats: (.txt) – plain text and (.rtf) – “rich text format”.

Binary Files

Binary files display data in encoded form (using only zeros (0) and ones (1) instead of simple characters). In most cases, they are just sequences of bits. They are stored in the format .bin.

File Operations in Python

Any operation with a file can be broken down into three major stages:

  1. Opening a file
  2. Performing an operation (write, read)
  3. Closing the file

Opening a file in Python

The very first operation to work with a file is to open it. In Python, the open () function (built-in function) is used to open a file in read and write mode. This function returns a file object. In the open () function, we define two arguments, in which the first is the name of the file and the second is the mode in which we want to open this file.

Syntax:
filex = open(“examplefile.txt”, “r”)

In the above example, the user wants to open a file named “abc.txt” in read mode. Likewise, users can open a file in different modes such as “w” for write mode and “a” for append mode. In Python, the user can also specify the binary or text mode in which he wants to open the file. The user is not required to specify the file mode, if the mode is not specified, then by default Python will open the file in read mode “r”. Let us examine the various different file access modes available in Python.

ModeFunction description
“R”Opens a file in read mode
“W”Opens a file in write mode
“A”Opens a file in append mode (append text to the end of the file)
“X”Creates the specified file, returns an error if the file already exists
“G +”Opens a file in read / write mode
“B”Opens a file in binary mode (in the case of executable .exe/.bin files)
“T”Opens a file in text mode

The modes can be combined, that is, for example, ‘rb’ – read in binary mode. By default, the mode is ‘rt’ that is read in text mode.

Performing Operation on the Files(Write/ Read)

Read( ) method:  This method reads the entire file at a time. The method returns \ n for newline. Once the entire file is complete, we get a whole blank line.

This is line 1
This is line 2
file = open (“example.txt”, 'r') print file.read() ​// This is line 1
// This is line 2

Readline( ) method: This method is used to read a file one line at a time until a \ n character is found in the file. It adds \ n at the end of the line.

file = open (“example.txt”, 'r') print file.readline() ​// This is line 1

Readlines( ) method: This method is used to read the entire file, but line by line. It updates the file for every line it returns.

file = open (“example.txt”, 'r') print file.readlines() ​//This is line 1
​// This is line 2

Read (n) method: This method is used when we want to read a specified length of characters in a file.

File = open (“example.txt”, 'r') print read(5) ​// 'This ' (including 1 space after s) (read 5 characters of a file).

Write( ) method in Python

To write a file in Python, we first need to open the file in write mode “w”, add “a” or throw an exception mode “x”. There is a slight difference between add and write mode in Python, and you need to be very careful with this, as the add method adds content to the end of the file, meaning it will not affect the data if the file is already created and has some data in it. But the write method will overwrite the contents of the file if the file with some data is already present. This method returns nothing.

filex = open (“example.txt”, 'r+') filex.write
(“First Line\n”) filex.write (“Second Line\n”) filex.close()

Writelines( ) method: The writelines () method is also used to write a sequence of lines to a file.

filex = open (“example.txt”, 'w')
lines = (“First Line”, “Second Line”) filex.writelines(lines)
filex.close()

Leave a Comment