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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago