Python File Handling Create Open

Python File Handling

Table of Contents

Python File handling a method to store the output of the program to a file or take input from the file. File handling is a key concept in the programming world. File handling used in almost every kind of project. For example, you are creating an Inventory management system. In the inventory management system, you have data related to sales and purchases so you need to store that data somewhere. Using Python file handling you can store that data into the file. If you are trying to perform some analysis on the data then you must be provided with data in the form comma separated file or Microsoft Excel file. Using file handling you can read data from that file and also store output back into that file.

While using file handling there are different types of modes available. Just have a look at them we will explain them in detail.

  • r “, for reading.
  • w “, for writing.
  • a “, for appending.
  • r+ “, for both reading and writing

Create file 

Let’s take a look at how to create a file using Python programming language.

Take a look at the left side we have only hello.py file.  Python File Handling

Now let’s execute the code.

f = open("data.txt","w+")

w+ stands for: Open a file for writing and reading.

The file with name data.txt has been created.

Python File Handling

Open and write into file

We will be using the above-created file. Let’s write some data into the file using code.

f = open("data.txt","w+")
for i in range(5):
	f.write("line " + str(i) + "\n")
Python File Handling

The file looks like this

Python File Handling

Append into file

“Write” option erases all the previous data present in the file. For appending data into an existing file we need to use a mode of “a”.

Let’s take a look at the code.

f = open("data.txt","a")
for i in range(2):
	f.write("appended lines " + str(i) + "\n")
Python File Handling

The data.txt file will look like this

Python File Handling

Read data from file

Let’s take a look at code to read data from the data.txt file.

f.read function output all the data present in the file.

f = open("data.txt","r")
print(f.read())
Python File Handling

If we need to read the data line by line we use readline() function.

Python File Handling

For reading first two lines.

Python File Handling

2 Responses

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class