Home » How to perform File IO operations in Python

How to perform File IO operations in Python

How to perform File I/O operations in Python

Hello guys, welcome back to programminginpython.com! Here in this post, I will show you how to perform different File IO operations in Python, like opening a file, reading content from the file, writing data to a file, and all the stuff. You can do most of the operations I just mentioned by using a file object.

Program on GitHub

Check this video on YouTube here.

Opening a file

If you want to perform any operations like reading, appending, or writing, first, you must open a file. You can open a file by using Python’s built-in function open(). This open() the function takes 3 arguments, they are the file nameaccess mode and buffering.

 

some_file_object = open(file_name access_mode, buffering)

The 3 parameters,

file_name – This parameter contains the name of the file which you want to access or perform some operations on it.

access_mode – This access_mode determines in which mode the file should open, i.e reading(‘r‘), writing(‘w‘), appending(‘a‘), reading and writing(‘r+‘), reading in binary format(‘rb‘) and many other modes. Below is a list of all the access modes.

File IO Operations in Python
File IO Operations in Python

buffering – This buffering is an optional parameter if you want a buffering option you set its value to 1, else 0 for no buffering, if you set it to greater than 1, it will start buffering from that buffer size.

File Attributes

Once a file is opened, you can get the values of different attributes like the name of the file, the mode of the file, and whether the file is opened or closed.

file_attributes = open("test.txt", "wb")
print("Name of the file: ", file_attributes.name)
print("Closed or not : ", file_attributes.closed)
print("Opening mode : ", file_attributes.mode)

When you execute the above snippet, it produces the following output.

File IO Operations in Python
File IO Operations in Python

Program on GitHub

Writing to a file

For writing content to a file, you first need to open() it in writing mode, any of w, w+. `wb`, wb+ these modes can be used to write content to a file.

You can write either in binary format or normal text format. If you write in a binary format you need to convert the content to bytes.

file_write = open("test.txt", "wb")
file_write.write(bytes("Python is a great language.", 'UTF-8'))
file_write.close()

Without binary format,

file_write = open("test.txt", "w")
file_write.write("Python is a great language.")
file_write.close()

Both the above snippets create a new file if the file does not exist and if the file exists, it overwrites the content.

Program on GitHub

Reading from a file

For reading the content in a file, you need to open() the file, and then use the Python read() function to read the data.

# Open a file
file_read = open("test.txt", "r+")
text = file_read.read()
print("Read String is : ", text)
file_read.close()

You can open the file in any mode which supports reading a file.

Appending content to a file

When You need to add some extra content to the existing data, you should open the file in append mode, and do the rest as you will do in write mode. It is similar to the write mode which I have shown in the above paragraphs, the main difference is the write mode overwrites the content but here the append mode adds to the existing content.

# Open a file
fo_append = open("test.txt", "a")
fo_append.write("\nPython is a powerful language.")
fo_append.close()

So now if I run the above snippet, it adds an extra line to the original content.

Program on GitHub

Delete a file

If you need to delete any file, then, in that case, you can use Python’s built-in function remove() to delete a file. However, you need to import the `os` module to do this and pass a file name you want to delete as an argument to remove() function.

import os

#delete a file
os.remove("test.txt")

That is how you can handle different file operations in Python. Below is the complete code snippet related to the file handling I/O operations covered above.

__author__ = 'Avinash'
import os

# Different file attributes
file_attributes = open("test.txt", "wb")
print("Name of the file: ", file_attributes.name)
print("Closed or not : ", file_attributes.closed)
print("Opening mode : ", file_attributes.mode)
file_attributes.close()

# Write to a file in binary format
file_write_bytes = open("test.txt", "wb")
file_write_bytes.write(bytes("Python is a great language.", 'UTF-8'))
file_write_bytes.close()

# Write to a file
file_write = open("test.txt", "w")
file_write.write("Python is a great language.")
file_write.close()

# Reading from a file
file_read = open("test.txt", "r+")
text = file_read.read()
print("Read String is : ", text)
file_read.close()

# Append to a file
file_append = open("test.txt", "a")
file_append .write("\nPython is a powerful language.")
file_append.close()

# Delete a file
os.remove("test.txt")

Program on GitHub

Also please feel free to check other posts on Python Lists, Python Tuples, or Python GUI programming.

Online Python Compiler

Leave a Reply

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