What are Files?

A File in a computer is defined as a pointer to a memory location on the secondary storage device (it can be Hard Disk, USB, SSD, etc.). Files allow managing and organizing digital data conveniently. Without Files, the user needs to remember the memory location of the data required.

Opening Python Files

Python language provides some inbuilt file handling functions and methods to the programmer. A Python program that can access a file needs to follow these steps:

  1. Opening the File
  2. Reading from or Writing into the File
  3. Closing the Object File

The open() function is used to open a new file stream for accessing a file. This function takes a relative or complete path along with the access mode as the two arguments. This function is used to return a file object.

For example

			

#relative file path
goodies_file = open("goodies.txt", 'r')   

#absolute File path
readme_file = open("/home/mysys/programming/readme.txt", 'r')     
  
				

File Opening Modes

Access modes available in Python are as follows:

 

Access Mode Description
r Read-Only Mode.
w Write Mode creates a new file if it's already not present at the path. Else, it will overwrite the contents of the existing file.
a Append Mode creates a new file if it's already not present at the path. Else, it will append the new file after the current data present in the existing file.
x Exclusive Creation Mode. Raises an error if that file exists. Else creates a new file with the specified name and opens it in write mode.
b Opens the file in Binary Mode.
t Opens the file in Text Mode.
+ Allows a file to read from and write to the file. For example, a+, x+ etc.

 

How to read file in Python

For reading data from a file, initially, we need to pass the 'r' access mode (read mode) to the open() function. For reading the contents of a file, the read() method is used. Like,

 

			

goodies_file = open("goodies.txt", 'r')   
print(goodies_file.read())

				

The read() method takes the size as an argument that specifies the number of bytes of the data in the file to read. By default, the read() method reads the file till the EOF (End of File).

The seek() function is used to modify the offset of the cursor in the file. Like this

			

goodies_file = open("goodies.txt", 'r')   
goodies _file.seek(3)
print(goodies_file.read())

				

To check the current offset of the cursor, the tell() function is available.

			

goodies_file = open("goodies.txt", 'r')   
print(goodies_file.read(10))
print(goodies_file.tell())

				

Another function i.e., the readline() function is used instead of read(). It reads one line at a time from the file. It stops reading when a newline character '\n' is encountered in the file. Like this

			

goodies_file = open("goodies.txt", 'r')   
print(goodies_file.readline())
print(goodies_file.readline())
print(goodies_file.readline())

				

How to close file in Python

It is the programmer's responsibility to manage the resources used by the program and free up unnecessary resources. So, the unnecessary file objects must be closed after their purpose is fulfilled. In Python, the close() method is used to achieve this. Like this.

			

goodies_file = open("goodies.txt", 'r')   
print(goodies_file.readline())
print(goodies_file.readline())
print(goodies_file.readline())
goodies_file.close()

				

Generally, file-related code is performed in the try...finally blocks. This is done because if the code raises an error before closing the file properly, the data inside the file may become corrupted. Code that handles File I/O should be written in the try block while the code related to closing the file object is put inside the finally block. Like this

			

try:
   goodies_file = open("goodies.txt", 'r')   
   print(goodies_file.readline())
   print(goodies_file.readline())
   print(goodies_file.readline())
  
finally:
   goodies_file.close()

				

Python with Statement

with statement makes the process of handling file objects easy and simple for the programmer. This closes the file stream automatically when its code block ends. Like this

			

with open('goodies.txt','r') as goodies_file:
   print(goodies_file.readline())
   print(goodies_file.readline())
   print(goodies_file.readline())
   print(goodies_file.read())      #will raise error as the file is automatically closed

				

Python Writing Files

We can write string data with the help of the write() method into the file. This method returns a count of bytes that were written to the file.

			

with open(' goodies.txt','a') as goodies_file:
   print(goodies_file.write("\nNew Text"))
   # print(goodies_file.readline())
   # print(goodies_file.readline())
   # print(goodies_file.readline())

with open('goodies.txt','r') as goodies_file:
   # print(goodies_file.readline())
   # print(goodies_file.readline())
   # print(goodies_file.readline())

   print(goodies_file.read())

				

File Methods in Python

Method Description
read() This method reads a file until a specified number of bytes strike or until the EOF(End of File).
write() Write methods are used to write the specified string or characters to the file.
close() This is used to close a file stream or object specified. If the file is already closed, then this method will do nothing.
seek() Move the offset of the cursor to a particular offset.
tell() Return the current offset of the cursor in the file.
readline() Read a line from the file.
readlines() Returns a list with each file line as a string element.
writelines() Writes the elements of the specified list into the file.
seekable() This method returns a True Boolean value if the file object allows seeking.
readable() This method returns True Boolean value if the file object is readable.
flush() Flush the write buffer of the file
truncate() This method reduces or resizes the file object to a particular number of bytes.