File Handling Python With Examples | Python Input-Output Awesome Tips

  1. What is a file?
  2. What is file encoding, like ASCII or utf-8, etc?
  3. What is File Access Mode? List of all file access modes in file handling operation.
  4. Which library is required to perform file handling or file input-output action?
  5. How to perform file handling operations in python?
    1. Open a file (new or existing)
    2. Read or write to the file
    3. Close the file
    4. Example: Performing basic file input-output (writing/reading) operation in python.
  6. Tips of file handling in python.
  7. List of file handling functions in python.
  8. Examples of file handling operations in python.

1. What is a file?

A file is a named object on a system (computers/mobiles/servers) that contains data within it. This data can be a text file, audio or video stream, application, executable file, etc.

Jump to the top of the page↵

2. What is file encoding, like ASCII or utf-8, etc?

File encoding is the way to store the character set used in the file in the computer system. In python, input output operation is used the encoding standard to read or write the files.  Based on the characters used you can use the below file encoding

  1. US-ASCII
    When we use the characters only from US-ASCII. It stores a single character in of 7 bits.
  2. UTF-8
    For character set of EBCDIC and GB18030. It stores a single character in 8 bits.
  3. UTF-16
    This encoding is useful when we want to use all English characters & Asian characters. Each character is encoded in 2 bytes, ie. It stores a single character in 16 bits.
  4. UTF-32
    It is not used very frequently. It takes lots of memory. Each character is encoded in 4 bytes, ie. It stores a single character in 32 bits.

Jump to the top of the page↵

2.1 Example: Encoding a character ‘A’ with a different encoding standard.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul  9 09:09:05 2021
website : http://mycloudplace.com
@author: mycloudplace
"""
if __name__ == "__main__":
    input_str = "A"
    print("'A' encoded in ascii as  : ",input_str.encode('ascii'))
    print("'A' encoded in utf-8 as  : ",input_str.encode('utf-8'))
    print("'A' encoded in utf-16 as : ",input_str.encode('utf-16'))
    print("'A' encoded in utf-32 as : ",input_str.encode('utf-32'))

OUTPUT:

'A' encoded in ascii as  :  b'A'
'A' encoded in utf-8 as  :  b'A'
'A' encoded in utf-16 as :  b'\xff\xfeA\x00'
'A' encoded in utf-32 as :  b'\xff\xfe\x00\x00A\x00\x00\x00'

For more about encoding please click here. The same encoding is used while reading or writing the file in python.

Jump to the top of the page↵

3. What is File Access Mode? List of all file access modes in file handling python.

File access mode is used to perform  all input output operations in python like reading, write or append. Below are the file access modes used in file handling operation in python.

S.No. Access mode Description
1 r It opens the file to read-only mode.
2 rb It opens the file to read-only in binary format.
3 r+ It opens the file to read and write both.
4 rb+ It opens the file to read and write both in binary format.
5 w It opens the file to write only.
6 wb It opens the file to write only in binary format.
7 w+ It opens the file to write and read both.
8 wb+ It opens the file to write and read both in binary format.
9 a It opens the file in the append mode.
10 ab It opens the file in the append mode in binary format.
11 a+ It opens a file to append and read both.
12 ab+ It opens a file to append and read both in binary format.

Jump to the top of the page↵

4. Which library is required to perform file handling or file input-output operations?

We generally use the IO module to perform file input output operations in python. We can also perform the basic actions with the standard library.

Syntax to import io module

import io

Jump to the top of the page↵

5. How to perform file handling operations in python?

File handling in python can be performed using the standard file handling library and methods. Below are the operations on file handling in python

  • Open a file (new or existing)
  • Read or write to the file
  • Close the file
5.1 Open a file (new or existing)

This is the first step to work with file handling in python. You can open a file(new or existing) using the Open() method. The Open() method takes 2 arguments

  1. Filename with complete path
  2. File mode

Syntax to open a file in python

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

Jump to the top of the page↵

5.2 Read or Write to the file

After opening the file you can perform read or write operation, to perform read/write you can also use the ‘with’ statement.

Syntax of reading/writing to a file in python

file_obj= open(<file-name>, <access-mode>,<encoding>)

Syntax of reading/writing to a file in python using the ‘with’ statement

with open(<file-name>, <encoding>) as file_obj:
        # write code goes here

Jump to the top of the page↵

5.3 Close the file

After performing all input output operations like read/write/append, we finally need to close the file. We close the file to release the resource. You can use  the Close() method to close the file

Syntax of closing a file in python

file_obj.close()

Jump to the top of the page↵

5.4 Example: Performing basic file input output (writing/reading) operation in python.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 19 16:52:51 2021
website : http://mycloudplace.com
@author: mycloudplace
"""
if __name__ == "__main__":
    file_name = "abc.txt"
    print("Opening the file",file_name,"in writing mode")
    file_obj = open(file_name, 'w', encoding='utf-8')
    file_obj.writelines("Hello, This is sample text.") #adding a line to file
    file_obj.close() #closing the file
    print("We have successfully created a file.")
    
    print("Below we are going to read the above created file")
    file_obj_read = open(file_name, 'r', encoding='utf-8')
    print(file_obj_read.read())

OUTPUT:

Opening the file abc.txt in writing mode
We have successfully created a file.
Below we are going to read the above created file
Hello, This is sample text.

Jump to the top of the page↵

6. Tips of file handling in python.

  1. Try to use with clause wherever possible.
  2. Always use try..catch block to perform file operation.
  3. Use encoding wherever possible.
  4. Always use buffering when you don’t know the size of the file you are going to deal with.
  5. Before opening a file it is always better to check if the file is already closed. This can be checked using the closed attribute.
  6. If you are dealing with the encoding & decoding of string and if you are strict with it, then use errors argument while opening the file.
    file_obj= open(<file-name>, <access-mode>,<encoding>, errors=“strict”)
  7. Use the readlines() function to read the content of the file one by one.
  8. Use os.getcwd() to get current working directory.

Jump to the top of the page↵

7. List of file handling functions in python.

  1. open(): It Opens the file to perform file input output operation.
  2. close(): It closes an opened file. It does not affect if the file is already closed.
  3. flush(): It flushes the write buffer of the file stream.
  4. isatty(): It returns True if the file stream is interactive else False.
  5. readable(): It returns True if the file stream can be read from.
  6. read(n): It reads at most n characters from the file. It reads till the end of the file if it is negative or None.
  7. readline(n=-1): It reads and returns one line from the file. Reads in at most n bytes if specified.
  8. readlines(n=-1): It reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.
  9. seek(offset,from=SEEK_SET): It changes the file position to offset bytes, about from (start, current, end).
  10. seekable(): It returns True if the file stream supports random access.
  11. tell(): It returns the current file location.
  12. truncate(size=None): It resizes the file stream to size bytes. If the size is not specified, resizes to the current location.
  13. writable(): It returns True if the file stream can be written to.
  14. write(str): It writes the string str to the file and returns the number of characters written.
  15. writelines(lines): It writes a list of lines to the file.
  16. fileno(): It returns an integer number of the file.

Jump to the top of the page↵

8. Examples of file handling operations in python.

Writing a program in python to read the first 4 characters from the file. Also, read the first 5 lines from the file.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 19 16:52:51 2021
website : http://mycloudplace.com
@author: mycloudplace
"""
if __name__ == "__main__":
    file_name = "abc.txt"
    with open(file_name,'w', encoding='utf-8') as file_obj:
        file_obj.write("First line." + "\n")
        file_obj.write("Second line." + "\n")
        file_obj.write("Third line." + "\n")
        file_obj.write("Fourth line." + "\n")
        file_obj.write("Fifth line." + "\n")
        file_obj.write("Sixth line." + "\n")
        file_obj.write("Seventh line." + "\n")
        file_obj.write("Eighth line." + "\n")
        file_obj.write("Ninth line." + "\n")
        file_obj.write("Tenth line." + "\n")
        
    print("The first 4 characters from the file")
    
    file_obj_read = open(file_name,'r', encoding='utf-8')
    print(file_obj_read.read(4))
    
    print("Reading the first 5 lines from the file")
    file_obj_read.seek(0) #Moving the cursor at the beginning of the file
    
    number_of_lines=5
    n=1
    while n <= number_of_lines:
        print(file_obj_read.readline())
        n+=1
    
    file_obj_read.close()

OUTPUT:

The first 4 characters from the file
Firs
Reading the first 5 lines from the file
First line.

Second line.

Third line.

Fourth line.

Fifth line.

Jump to the top of the page↵

Below is our previous articles on python

4 thoughts on “File Handling Python With Examples | Python Input-Output Awesome Tips”

  1. Pingback: A to Z of Python exception handling | Python try catch with example - Mycloudplace

  2. Pingback: Python reporting libraries | Python reporting tools to generate interactive and beautiful reports - Mycloudplace

Leave a Comment

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