In this Python tutorial we will work on file handling. You will learn how to read,create,write delete files and also learn some more inbuilt python file handling functions.


Python File Handling: Create, Open, Append, Read, Write

In Python, there is no need for importing external library to read and write files. Python provides an inbuilt function for creating, writing and reading files.

In this tutorial, we will learn

  • How to Create a Text File
  • How to Append Data to a File
  • How to Read a File
  • How to Read a File line by line
  • File Modes in Python

How to Create a Text File

With Python you can create a .text files (guru99.txt) by using the code, we have demonstrated here how you can do this

Step 1)

f= open("guru99.txt","w+")
  • We declared the variable f to open a file named guru99.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or operation we want to do on the file
  • Here, we used “w” letter in our argument, which indicates write and will create a file if it does not exist in library
  • Plus sign indicates both read and write.
  • The available option beside “w” are, “r” for read, and “a” for append

Step 2)

for i in range(10):
     f.write("This is line %d\r\n" % (i+1))
  • We have a for loop that runs over a range of 10 numbers.
  • Using the write function to enter data into the file.
  • The output we want to iterate in the file is “this is line number”, which we declare with write function and then percent d (displays integer)
  • So basically we are putting in the line number that we are writing, then putting it in a carriage return and a new line character

Step 3)

f.close() 
  • This will close the instance of the file guru99.txt stored

Here is the result after code execution

Python FILE Tutorial: Create, Append, Read, Write

When you click on your text file in our case “guru99.txt” it will look something like this

Python FILE Tutorial: Create, Append, Read, Write

How to Append Data to a File

You can also append a new text to the already existing file or the new file.

Step 1)

f=open("guru99.txt", "a+")

Once again if you could see a plus sign in the code, it indicates that it will create a new file if it does not exist. But in our case we already have the file, so we are not required to create a new file.

Step 2)

for i in range(2):
     f.write("Appended line %d\r\n" % (i+1))

This will write data into the file in append mode.

![https://www.guru99.com/images/Pythonnew/Python17.3.jpg)

You can see the output in “guru99.txt” file. The output of the code is that earlier file is appended with new data.

Python FILE Tutorial: Create, Append, Read, Write

How to Read a File

Not only you can create .txt file from Python but you can also call .txt file in a "read mode"®.

Step 1) Open the file in Read mode

f=open("guru99.txt", "r")

Step 2) We use the mode function in the code to check that the file is in open mode. If yes, we proceed ahead

if f.mode == 'r':

Step 3) Use f.read to read file data and store it in variable content

contents =f.read()

Step 4) print contents

Here is the output

Python FILE Tutorial: Create, Append, Read, Write

How to Read a File line by line

You can also read your .txt file line by line if your data is too big to read. This code will segregate your data in easy to ready mode

Python FILE Tutorial: Create, Append, Read, Write

When you run the code (f1=f.readlines()) for reading the file or document line by line, it will separate each line and present the file in a readable format. In our case the line is short and readable, the output will look similar to the read mode. But if there is a complex data file which is not readable, this piece of code could be useful.

File Modes in Python

Here is the complete code

Python 2 Example

def main():
     f= open("guru99.txt","w+")
     #f=open("guru99.txt","a+")
     for i in range(10):
         f.write("This is line %d\r\n" % (i+1))
     f.close()   
     #Open the file back and read the contents
     #f=open("guru99.txt", "r")
     #   if f.mode == 'r': 
     #     contents =f.read()
     #     print contents
     #or, readlines reads the individual line into a list
     #fl =f.readlines()
     #for x in fl:
     #print x
if __name__== "__main__":
  main()

Python 3 Example

def main():
    f= open("guru99.txt","w+")
    #f=open("guru99.txt","a+")
    for i in range(10):
         f.write("This is line %d\r\n" % (i+1))
    f.close()
    #Open the file back and read the contents
    #f=open("guru99.txt", "r")
    #if f.mode == 'r':
    #   contents =f.read()
    #    print (contents)
    #or, readlines reads the individual line into a list
    #fl =f.readlines()
    #for x in fl:
    #print(x)
if __name__== "__main__":
  main()

Summary

  • Python allows you to read, write and delete files
  • Use the function open(“filename”,“w+”) to create a file. The + tells the python interpreter to open file with read and write permissions.
  • To append data to an existing file use the command open(“Filename”, “a”)
  • Use the read function to read the ENTIRE contents of a file
  • Use the readlines function to read the content of the file one by one.

File Handling in Python

Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and short. Python treats file differently as text or binary and this is important. Each line of code includes a sequence of characters and they form text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.

Working of open() function

We use open () function in Python to open a file in read or write mode. As explained above, open ( ) will return a file object. To return a file object we use open() function along with two arguments, that accepts file name and the mode, whether to read or write. So, the syntax being: open(filename, mode). There are three kinds of mode, that Python provides and how files can be opened:

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

One must keep in mind that the mode argument is not mandatory. If not passed, then Python will assume it to be “ r ” by default. Let’s look at this program and try to analyze how the read mode works:

# a file named "geek", will be opened with the reading mode. 
file = open('geek.txt', 'r') 
# This will print every line one by one in the file 
for each in file: 
	print (each) 

The open command will open the file in the read mode and the for loop will print each line present in the file.

Working of read() mode

There is more than one way to read a file in Python. If you need to extract a string that contains all characters in the file then we can use file.read(). The full code would work like this:

# Python code to illustrate read() mode 
file = open("file.text", "r") 
print file.read() 

Another way to read a file is to call a certain number of characters like in the following code the interpreter will read the first five characters of stored data and return it as a string:

# Python code to illustrate read() mode character wise 
file = open("file.txt", "r") 
print file.read(5) 

Creating a file using write() mode

Let’s see how to create a file and how write mode works:
To manipulate the file, write the following in your Python environment:

# Python code to create a file 
file = open('geek.txt','w') 
file.write("This is the write command") 
file.write("It allows us to write in a particular file") 
file.close() 

The close() command terminates all the resources in use and frees the system of this particular program.

Working of append() mode

Let’s see how the append mode works:

# Python code to illustrate append() mode 
file = open('geek.txt','a') 
file.write("This will add this line") 
file.close() 

There are also various other commands in file handling that is used to handle various tasks like:

rstrip(): This function strips each line of a file off spaces from the right-hand side.
lstrip(): This function strips each line of a file off spaces from the left-hand side.

It is designed to provide much cleaner syntax and exceptions handling when you are working with code. That explains why it’s good practice to use them with a statement where applicable. This is helpful because using this method any files opened will be closed automatically after one is done, so auto-cleanup.

Example:

# Python code to illustrate with() 
with open("file.txt") as file: 
	data = file.read() 
# do something with data 

Using write along with with() function

We can also use write function along with with() function:

# Python code to illustrate with() alongwith write() 
with open("file.txt", "w") as f: 
	f.write("Hello World!!!") 

split() using file handling

We can also split lines using file handling in Python. This splits the variable when space is encountered. You can also split using any characters as we wish. Here is the code:

# Python code to illustrate split() function 
with open("file.text", "r") as file: 
	data = file.readlines() 
	for line in data: 
		word = line.split() 
		print word 

There are also various other functions that help to manipulate the files and its contents. One can explore various other functions in Python Docs.

#python #web-development #machine-learning

Python File Handling Tutorial
5.10 GEEK