Categories: python

File Handling in Python

What is File Handling?
  • Every web app requires the handling of files. File handling is critical when data must be stored permanently in a file.
  • A file is a named location on the disc where related information is stored.
  • After the program has terminated, we can access the stored information (non-volatile).
File Access Modes:

Access Modes govern the activities you can perform on the opened file. These describe how to use the file once it has been opened. These modes also specify the location of the file handle within the file. A file handle, like a pointer, indicates where data should be read or written to the file.

In Python, the following are the details about the access mode :

ModeDescription
rReads from a file and returns an error if the file does not exist (default).
wWrites to a file and creates the file if it does not exist or overwrites an existing file.
xExclusive creation that fails if the file already exists.
aAppends to a file and creates the file if it does not exist or overwrites an existing file.
bBinary mode. Use this mode for non-textual files, such as images.
tText mode. Use only for textual files (default).
+Activates read and write methods.
Opening a File:

Python has an open() function that takes two arguments: the file name and the access mode in which the file is accessed. The function returns a file object that can be used to perform operations such as reading, writing, and so on.

Syntax:

file object = open(<file-name>, <access-mode>, <buffering>)

The files can be accessed using various modes like read, write, or append as mentioned above.

Example:

fileptr = open("file1.txt","r")    
    
if fileptr:    
    print("file is opened successfully") 

In the preceding code, we passed filename as the first argument and opened the file in read mode by specifying r as the second argument. The fileptr holds the file object, and if the file is successfully opened, the print statement is executed.

Closing a File:

The close() method of a file object flushes any unwritten data and closes the file object, preventing further writing.

When a file’s reference object is reassigned to another file, Python automatically closes the file. It is best to use the close() method to close a file.

Syntax:

fileobject.close()

Example:

fileptr = open("file1.txt","r")    
    
if fileptr:    
    print("file is opened successfully")    
    
#closes the opened file    
fileptr.close() 

We cannot perform any operations on the file after it has been closed. The file should be properly closed. If an exception occurs while performing some file operations, the program exits without closing the file.

Note: also read about Python Exception Handling – III(Raise Keyword )

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

2 days ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago