Python File Operation

File handling is one of the important operations that a programming language provides.

Loading…

What is a file?

The file provides a storage mechanism in a program to store our data. It is a named location on disk that can store our information which is stored permanently in the hard disk. As our program is executed in Random Access Memory (RAM), it loses its data in variables when the program exists.

File operation takes place in three stages in Python:-

  1. Open a file
  2. Perform operation ( read or write )
  3. Close the file

How to open a file in Python?

Python provides open() function that helps to open a file in various modes. The function returns a file object which can be used to perform various operations like reading, writing, etc.

The syntax to use the open() function is given below.

file = open(, , )

The files can be accessed using various modes like read, write, or append. The following are the details about the access mode to open a file.

SN Access mode Description
1 r It opens the file to read-only. The file is by default open in this mode if no access mode is passed.
2 rb It opens the file to read only in binary format.
3 r+ It opens the file to read and write both.
4 rb+ It opens the file to read and write both in binary format.
5 w It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name.
6 wb It opens the file to write only in binary format. It overwrites the file if it exists previously or creates a new one if no file exists with the same name.
7 w+ It opens the file to write and read both. It is different from r+ in the sense that it overwrites the previous file if one exists whereas r+ doesn’t overwrite the previously written file. It creates a new file if no file exists.
8 wb+ It opens the file to write and read both in binary format. The file pointer exists at the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at the end of the previously written file if exists any. It creates a new file if no file exists with the same name.
10 ab It opens the file in the append mode in binary format. The pointer exists at the end of the previously written file. It creates a new file in binary format if no file exists with the same name.
11 a+ It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. It creates a new file if no file exists with the same name.
12 ab+ It opens a file to append and read both in binary format. The file pointer remains at the end of the file.
13 x Open a file for exclusive creation. If the file already exists, the operation fails.
14 + Open a file for updating (reading and writing)

Let us have a look at an example,

# opens the file hello.txt in read mode 
file_obj = open("hello.txt", "r")

if file_obj:
    print("File is opened successfully")

For this to be error-free, we need a hello.txt file to be created in the same folder where the program is written.

It is always good practice to include encoding while dealing with files,

file = open(“test.txt”,mode = ‘r’,encoding = ‘utf-8’)

How to close a file Using Python?

Once the file operations are completed, we require to close the file in order to free up memory space.

The syntax to use the close() method is given below.

file_obj.close()
# opens the file hello.txt in read mode
file_obj = open("hello.txt", "r")

if file_obj:
    print("File is opened successfully")
    
file_obj.close()

A safer way to open and close a file can be done using try-finally block,

try:
   f = open("hello.txt",encoding = 'utf-8')
   # perform file operations
finally:
   f.close()

With statement for handling files

The best way to open a file is by using with the statement. This ensures that the file is closed when the block inside is exited. We don’t need to explicitly call the close() method. It is done internally.

with open("hello.txt",encoding = 'utf-8') as f:
   # perform file operations

What are the file Object Attributes?

# Attribute & Description
1 file.closed
Returns true if the file is closed, false otherwise.
2 file.mode
Returns access mode with which file was opened.
3 file.name
Returns name of the file.

Let’s see these attributes in actions:-

fo = open("hello.txt", "wb")
print("Name of the file: ", fo.name)
print("Closed or not : ", fo.closed)
print("Opening mode : ", fo.mode)
fo = open("hello.txt", "wb")
print("Name of the file: ", fo.name)
print("Closed or not : ", fo.closed)
print("Opening mode : ", fo.mode)

How to write to File Using Python?

To write to a file in python, we can open file in any one mode viz. write ‘w’, append ‘a’ or exclusive creation ‘x’ mode.

with open("hello.txt", 'w', encoding ='utf-8') as f:
   f.write("Welcome to Programming World.\n")
   f.write("This is a file operation.\n")
   f.write("It contains three lines.\n")

This creates a hello.txt file that will contain the following content:-

Welcome to Programming World.
This is a file operation.
It contains three lines.

How to read a file in Python?

We can use read(size) function to read from the file where size is the number of characters to be read from the file. If the size is not defined, it reads all the data.

f = open("hello.txt", 'r', encoding = 'utf-8')
print("### Read first 7 characters from hello.txt")
print(f.read(7))

print("\n### Read rest of the contents")
print(f.read())

f.seek(0)
print("\n### Read all of the contents")
print(f.read())

f.close()

The output of the above program is:-

### Read first 7 characters from hello.txt
Welcome
### Read rest of the contents
to Programming World.
This is a file operation.
It contains three lines.### Read all of the contents
Welcome to Programming World.
This is a file operation.
It contains three lines.

To Loop through lines in a file, we can use for loop.

f = open("hello.txt", 'r', encoding = 'utf-8')
for line in f:
    print(line, end = '')

f.close()

Similarly, we can use readline() function to read line by line. The readlines() function will output the list of lines that can be iterated to get the contents.

What are File Methods provided by Python?

SN Method Description
1 file.close() It closes the opened file. The file once closed, it can?t be read or write any more.
2 File.fush() It flushes the internal buffer.
3 File.fileno() It returns the file descriptor used by the underlying implementation to request I/O from the OS.
4 File.isatty() It returns true if the file is connected to a TTY device, otherwise returns false.
5 File.next() It returns the next line from the file.
6 File.read([size]) It reads the file for the specified size.
7 File.readline([size]) It reads one line from the file and places the file pointer to the beginning of the new line.
8 File.readlines([sizehint]) It returns a list containing all the lines of the file. It reads the file until the EOF occurs using readline() function.
9 File.seek(offset[,from) It modifies the position of the file pointer to a specified offset with the specified reference.
10 File.tell() It returns the current position of the file pointer within the file.
11 File.truncate([size]) It truncates the file to the optional specified size.
12 File.write(str) It writes the specified string to a file
13 File.writelines(seq) It writes a sequence of the strings to a file.

 

Loading…