DEV Community

Praveen kumar
Praveen kumar

Posted on

File Handling in Python

It's hard to find anyone in the 21st century, who doesn't know what a file is.

When we say file, we mean of course, a file on a computer. There may be people who don't know anymore the "container", like a cabinet or a folder, for keeping papers archived in a convenient order. A file on a computer is the modern counterpart of this. It is a collection of information, which can be accessed and used by a computer program. Usually, a file resides on a durable storage. Durable means that the data is persistent, i.e. it can be used by other programs after the program which has created or manipulated it, has terminated.

A file or a computer file is a chunk of logically related data or information which can be used by computer programs. Usually a file is kept on a permanent storage media, e.g. a hard drive disk. A unique name and path is used by human users or in programs or scripts to access a file for reading and modification purposes.

Types of Files:

There are two types of Files:

  1. Text files - Files which stores character data are known as text file . for ex: demo.txt

  2. Binary files - Files which stores binary data like images, videos, audio etc are known as binary files . for ex: demo.mp3 etc

As a part of file handling in python we will learn

  • Opening a File / Creating & Opening a File:

    To perform any operation (like read or write) on a file, first we have to open that file. For this we should use Python's inbuilt function open() But at the time of opening a file , we need to specify the mode, which represents the purpose of opening file. demo_file = open(filename, mode) The allowed modes to open a file in Python are

1. **r :** This mode opens an existing file for read operation. The file pointer is positioned at the beginning of the file. If the specified file does not exist then we will get **FileNotFoundError**. This is also default mode.

<!-- -->
Enter fullscreen mode Exit fullscreen mode
```
python read-list.py
Traceback (most recent call last):
  File "D:\Software Training Classes\Pythonier\class-27\read-list.py", line 2, in <module>
    file=open("fruits1.txt",'r')
FileNotFoundError: [Errno 2] No such file or directory: 'fruits1.txt'
```
Enter fullscreen mode Exit fullscreen mode
1. **w :** This mode opens an existing file for write operation. If the file already contains some data then it will be overridden. If the specified file is not already available then this mode will create that file.

2. **a :** This mode opens an existing file for append operation. It won't override existing data. If the specified file is not already available then this mode will create a new file.

3. **r+ :** This mode is used to read and write data into the file. The previous data in the file will not be deleted. The file pointer is placed at the beginning of the file.

4. **w+** : This mode is used to write and read data. It will override existing data.

5. **a+ :** This mode is used to append and read data from the [file. It](<http://file.it/>) wont override existing data.

6. **x :** This mode is used to open a file in exclusive creation mode for write operation. If the file already exists then we will get FileExistsError.

<!-- -->
Enter fullscreen mode Exit fullscreen mode

Example:

demo_file = open("abc.txt","w")

Note: All the above modes are applicable for text files. If the above modes suffixed with 'b' then these represents for binary files. ie rb,wb,ab,r+b,w+b,a+b,xb

  • Closing a File:

    We use close() function to close a file.

    After completing of our operations on a file, it is highly recommended to close the file. Example: demo_file.close();

once opening a file we have access to the file object which has different properties.

Some important properties of the file object are:

  1. name : It gives name of opened file

  2. mode : It tells the Mode in which the file is opened

  3. closed : IT returns Boolean value indicates that file is closed or not

  4. readable() : It returns Boolean value indicates that whether file is readable or not

  5. writable() : It returns Boolean value indicates that whether file is writable or not.

Example

py-file.py

#file handling in python
demo_file = open("demo.txt","w")
#once opening a file we have access to the file object which has different properties.
print("File Name: ",demo_file.name)
print("File Mode: ",demo_file.mode)
print("Is File Readable: ",demo_file.readable())
print("Is File Writable: ",demo_file.writable())
print("Is File Closed : ",demo_file.closed)
demo_file.close()
print("Is File Closed : ",demo_file.closed)
Enter fullscreen mode Exit fullscreen mode

demo.txt

python .\py-file.py
File Name:  demo.txt
File Mode:  w
Is File Readable:  False
Is File Writable:  True
Is File Closed :  False
Is File Closed :  True
Enter fullscreen mode Exit fullscreen mode

Writing data in a text file:

#We can write character data to the text files by using the following 2 methods.
#    1 write(str)
#   2 writelines(list of lines)
#opening a file in write mode
file = open("fruits.txt",'w')
#writing a single line using write() function
file.write('apple \n')
file.write('mango \n')
file.write('banana \n')
# closing the file
file.close()
Enter fullscreen mode Exit fullscreen mode

After execution we will get fruits.txt file as below

fruits.txt

apple 
mango 
banana
Enter fullscreen mode Exit fullscreen mode

NOTE:

In the above program, data present in the file will be overridden everytime if we run the program.

NOTE 2:

Instead of overriding if we want append operation then we should open the file as follows.

f = open("abcd.txt","a")
Enter fullscreen mode Exit fullscreen mode

NOTE 3:

while writing data by using write() methods, compulsory we have to provide line seperator(\n), otherwise total data should be written to a single line.

using writelines(list of lines)

add-animals.py

#demonstrating the writelines(list of characters)
file = open("animals.txt",'w')
wild_animal_list = ['Tiger','Lion','Cheetah','Leopard']
#wild_animal_list = ['Tiger \n','Lion \n','Cheetah \n','Leopard \n']
file.writelines(wild_animal_list)
file.close()
Enter fullscreen mode Exit fullscreen mode

after executing the above program we get a animals.txt file as below

animals.txt

TigerLionCheetahLeopard
Enter fullscreen mode Exit fullscreen mode

Reading Character Data from text files:

We can read character data from text file by using the different methods given below:

  1. read() : To read total data from the file.

  2. read(n) : To read 'n' characters from the file

  3. readline(): To read only one line

  4. readlines() : To read all lines into a list

CASE I : reading all the characters of a file

read-fruits.py

#program to read all characters of a file 
file=open("fruits.txt",'r') 
data=file.read() 
print(data) 
file.close()
Enter fullscreen mode Exit fullscreen mode

After executing the above program we will get the below output

python .\read-fruits.py
apple  
mango  
banana
Enter fullscreen mode Exit fullscreen mode

CASE II : Reading the first n characters of a file

read-fruits.py

#program to read all characters of a file 
file = open("fruits.txt",'r')
data=file.read(2) 
print(data) 
file.close()
Enter fullscreen mode Exit fullscreen mode

After executing the above program we get the below output

python .\read-fruits.py
ap
Enter fullscreen mode Exit fullscreen mode

CASE III : reading data line by line:

# reading the file line by line
file=open("animals.txt",'r') 
line1=file.readline() 
print(line1,end='') 
line2=file.readline() 
print(line2,end='') 
line3=file.readline() 
print(line3,end='') 
file.close()
Enter fullscreen mode Exit fullscreen mode

After executing the above we will get the below output

python .\read-fruits.py
TigerLionCheetahLeopard
Enter fullscreen mode Exit fullscreen mode

CASE IV : reading all lines into a list

#reading all lines into a list
file=open("fruits.txt",'r') 
lines=file.readlines() 
for line in lines: 
    print(line,end='') 
file.close()
Enter fullscreen mode Exit fullscreen mode

After executing the above program we get the below output

python .\read-list.py  
apple 
mango
banana
Enter fullscreen mode Exit fullscreen mode

Use of with keyword in File Handling

with keyword can be used for opening a file .We can use this to group file operation statements within a block. ie

#program to demonstrate with keyword in file handling
with open("language.txt","w") as file: 
    file.write("Python\n") 
    file.write("HTML\n") 
    file.write("CSS\n") 
    file.write("Bootstrap\n") 
    file.write("Django\n") 
    print("Is File Closed inside the with block: ",file.closed) 
print("Is File Closed outside the with block: ",file.closed)
Enter fullscreen mode Exit fullscreen mode

After executing the above program we get the below output:

in console.

python .\file-with.py
Is File Closed:  False
Is File Closed:  True
Enter fullscreen mode Exit fullscreen mode

language.txt

Python
HTML
CSS
Bootstrap
Django
Enter fullscreen mode Exit fullscreen mode

Special methods for file handling positions

  1. tell() - It return current position of the cursor(file pointer) from beginning of the file.

    tell() function ask can you please tell current cursor position from the file object.

    The position(index) of first character in files is zero just like string index.

    example:

    #demonstration of tell() which gives the position of the pointer 
    #from starting of the file.
    file=open("fruits.txt","r") 
    print(file.tell()) 
    print(file.read(2)) 
    print(file.tell()) 
    print(file.read(3)) 
    print(file.tell())
    

    After executing the above program we get the below output:

    python .\file-tell.py
    0
    ap
    2
    ple
    5
    
  2. seek() - It move cursor(file pointer) to specified location. This function answers Can you please seek the cursor to a particular location.

f.seek(offset, fromwhere)

Where
offset represents the number of positions

The allowed values for second attribute(from where) are
0---->From beginning of file(default value)
1---->From current position
2--->From end of the file
Enter fullscreen mode Exit fullscreen mode

Note: From above Python 2 supports all 3 values but Python 3 supports only zero.

file-seek.py

data="WE are here to learn python development" 
file=open("seek.txt","w") 
file.write(data) 
with open("abc.txt","r+") as file: 
    text=file.read() 
    print(text) 
    print("The Current Cursor Position: ",file.tell()) 
    file.seek(17) 
    print("The Current Cursor Position: ",file.tell()) 
    file.write("along with Django!!!") 
    file.seek(0) 
    text=file.read() 
    print("Data After Modification:") 
    print(text)
Enter fullscreen mode Exit fullscreen mode

After executing the above program we get the below output:

console:

python .\file-seek.py
WE are here to learn python development
The Current Cursor Position:  39       
The Current Cursor Position:  17       
Data After Modification:
WE are here to lealong with Django!!!nt
Enter fullscreen mode Exit fullscreen mode

seek.txt

WE are here to lealong with Django!!!nt
Enter fullscreen mode Exit fullscreen mode

Checking if a particular file exits or not:

we can check the existence of a particular file by using a function isFile() in the os module which tells whether a particular file exists or not?

import os
os.path.isfile(file-name)
Enter fullscreen mode Exit fullscreen mode

Q. Write a program to check whether the given file exists or not. If it is available then print its content?

#program to check if a file existence or not
import os,sys 
file_name=input("Enter File Name: ") 
if os.path.isfile(file_name): 
    print("File exists:",file_name) 
    file=open(file_name,"r") 
else: 
    print("File does not exist:",file_name) 
    sys.exit(0) 
print("The content of file is:") 
data=file.read() 
print(data)
file.close()
Enter fullscreen mode Exit fullscreen mode

Note: sys.exit(0) ===>To exit system without executing rest of the program. argument represents status code . 0 means normal termination and it is the default value.

After executing the above program we get the below output:

python .\file-check.py
Enter File Name: animal1
File does not exist: animal1
PS D:\Software Training Classes\Pythonier\class-27> python .\file-check.py
Enter File Name: animals.txt
File exists: animals.txt
The content of file is:
TigerLionCheetahLeopard
Enter fullscreen mode Exit fullscreen mode

Task : Create a file and insert you basic details . After that open the file again and update some more academic details of yours and check the current cursor of the file after that close the file.

Again write a program to open that that file and check where your cursor is after that move 500 characters ahead from the starting of the file and write something about your experience and finally print the output and close the file.

Top comments (0)