Python File Handling

In this tutorial we will discuss about Python file handling concepts. The tutorial will include opening file, closing file, reading from and writing to file.

Text files are a great way to store information. The normal text files stores data in the least possible memory size, generally in Kilobytes. Text Files are extremely easy to create and use. Moreover, it has cross-platform feature. Whether you create a text file in Windows or Linux, it can be transferred to another Operating System without any issue with the extension. Morever, every OS provides a basic tool to work around with basic text files.

File reading is an important concept in programming. Here, we are going to give you more information about Python file handling concepts.

 

Python File Handling

Opening and Closing a File

Syntax

variable=open("File Name","Access Mode")
variable.close()

 

To access a file, we need to open it into the system. The open() method is used to open the file into the system for reading or writing or both. The close() method is used to close the opened file.

The open() function takes in two parameters:
1. File Name
2. Access Mode (Reading/Writing/Both)

 

Example

var1=open("textset.txt","r")
var1.close()

 

Here, we have created a variable var1 which is assigned a value. The open() method is assigned to var1. We have taken a file named textset.txt that has a .txt extension. The mode of opening is read mode. As soon as we’re done with the file, we must close it to save the memory consumed by it.

 

Access Modes

“r” : This mode is used to read from a file. Python would display an error if the file doesn’t exist.

“w”: This mode is used to write to a file. The file contents are over-written by the new contents if the file exists, otherwise it will be newly created.

“a”: This mode is used to append to a file. The data is appended or added into the file if it exists otherwise its newly created.

“r+”: This mode is used to read from and write to a file. Python would display an error if the file doesn’t exist.

“w+”: This mode is used to write to and read from a file. The contents are overwritten if the file exists, if the file doesn’t exist, it is created.

“a+”: This mode is used to append first and then read from a file. The New data is appended to it if the file is already created. If the file doesn’t exist, it is created.

 

Reading from File

Example

# -*- coding: utf-8 -*-
var=open("/home/tusharsoni/Desktop/textset.txt","r")
a=var.read()
print(a)
var.close()

 

Output

Python File Handling 1

 

Note: The first line plays a very important role without which your code sometimes won’t work. You must use this statement if you are trying to use UTF-8 Characters.

The second line opens the file into the System. The open() method takes in two parameters. The first is the File Name or the complete location of the file to be accessed which is optional. Here, the file that we are reading data from is textset.txt. The next is the mode. Then, we use the read() function which actually takes in all the text written into the text file. After taking the value read by read() function in a, we print the variable a onto the console. After we are done with the file, we need to close the file using the close() method as if we don’t do it, it will remain in the memory consuming important space.

 

Read a Character from File

Syntax

print textset.readline(1)

 

The above function readline() is used to read a specific character at a specific location and then print it onto the console. The readline() function takes in a single parameter that specifies the number of characters that are to be read.

 

Example

# -*- coding: utf-8 -*-
var=open("/home/tusharsoni/Desktop/textset.txt","r")
print var.readline(1)
var.close()

 

Output

Python File Handling 2

 

Read a Single Line from File

Syntax

print textset.readline()

 

Example

# -*- coding: utf-8 -*-
var=open("/home/tusharsoni/Desktop/textset.txt","r")
print var.readline()
var.close()

 

The above program reads a text file line by line. So executing the above program will give you the output of the first line on the console.

 

Writing to File

We can write into a file using write mode. For this, we need to use the access mode as ‘w’ and also use the write() method. All the content of the file will be erased if it exists previously or else new file will be created.

 

Example

# -*- coding: utf-8 -*-
var=open("/home/tusharsoni/Desktop/textset.txt","w")
var.write("This is thecrazyprogrammer.com")
var.close()

 

The write() method do not add new line character in the end of the string.

 

Tell() Method

This method returns the current location or position of the read/write pointer within the file. This method doesn’t require any parameter to be passed in it.

 

Syntax

FileVariableName.tell()

 

Example

# -*- coding: utf-8 -*-
var=open("/home/tusharsoni/Desktop/textset.txt","r")
print var.readline()
fp = var.tell()
print(fp)
var.close()

 

Output

Python File Handling 3

 

Seek() Method

This method is used to set the file pointer to a particular position. Suppose, you want to goto the 5th character and start the printing after the 5th character, then seek() method is useful.

This method takes in two parameters.

First is the position which takes in the position at where you need to set the file pointer.

The second parameter is the source parameter which is an optional one. It accepts only one of the three values mentioned below:

0: This is the default value and indicates absolute file position.
1: This value provides relative seeking to the current file pointer location.
2: This value indicates relative seeking to the File’s ending character.

 

Syntax

FileVariableName.seek(position,source)

 

Example

# -*- coding: utf-8 -*-
var=open("/home/tusharsoni/Desktop/textset.txt","r")
var.seek(5)
fp = var.readline()
print(fp)
var.close()

 

Output

Python File Handling 4

 

Comment below if you find anything incorrect or have doubts regarding above Python file handling tutorial.

Leave a Comment

Your email address will not be published. Required fields are marked *