File Handling in Python 3-Complete Tutorial

file handling python 3

This File Handling in Python 3-Complete Tutorial is made for you. At the end of this tutorial, you will have full knowledge of the File Handling in Python 3.

Hello, & Welcome!

Part 18- File Handling in Python 3-Complete Tutorial

In this article of Python Tutorial, you will learn following-

  1. How to Create or Open a Text File?
  2. Close File in Python.
  3. Modes of File in Python.
  4. Writing Files in Python.
  5. Append Data to a File.
  6. Reading File in Python.

How to Create or Open a Text File?

In Python, you can create a .text file by using the open() method. Inside the open() method you need to pass the file name along with the path of the file.

Let’s see in the example-

data_file=open('files/data.txt')

Here, we are storing the “data.txt” file in the “data_file” reference variable. “files/data.txt” is the path of the file.

Close File in Python.

You can close any file by using close() function in Python. You can use a close() function when you don’t have any need for that file. A close() function leaves the memory space taken by that file.

Let’s see in the example, how to close any file?

data_file=open('files/data.txt')
data_file.close()

Here, we have closed the “data_file”, which we opened.

Modes of File in Python

There are different modes available in Python to perform Read and Write operations. We will discuss all modes here-

ModesDefinition
“r”You can use it to open a file for reading text.
“w”You can use it for writing something in text file. If the file doesn’t exist, so it can create a new file.
“a”If you wanna add something in your file, then use this append “a” to append something in a file.
“x”It is used to create a new file, if file exist already, then it fails.
“r+”It means read and write. It opens a file to read and write in the file.
“w+”It means write and read. It opens the file for writing and reading.
“a+”It is append and read. If the file doesn’t exist, then it will create a new file. It writes data at the end of the existing data.

Writing Files in Python

In order to write something in a file, first, you need to create a blank text file. Then inside this .py python file just write this lines of code-

with open('files/write.txt','w') as write_file:
write_file.write('Hey I am John, Python is awesome')

After writing this code, these strings are written in the write.txt file.

Here, ‘w’ is a mode to write something in the file. We have created a write.txt” file and inside that file, we have written the text.

Append Data to a File-

Append means adding something in the previous text. If you wanna add something in your text file then you can do it by append mode.

If you write again this code in a file-

with open('files/write.txt','w') as write_file:
write_file.write('Hey I am John, Python is awesome')

So it will override the first text, so to avoid it, you need to use append mode as “a”, so it will write the text at the end of the first text.

Let’s see in the example-

with open('files/write.txt','a') as write_file:
write_file.write('\n I love it so much, I dream python')

Here, this text is written after the first text like that-

OUTPUT-
Hey I am John, Python is awesome.
I love it so much, I dream python.

To write text from a new line use ‘\n’.

If you wanna write something from any list, then you need to write it like that-

quotes=[ 
        '\n Hello! its John'.
        '\n I love Python'.
        '\n It is very easy'.
      ]
with open('files/write.txt','a') as write_file:
write_file.writelines(quotes)

Here, “writelines” is a function to print lines. And “quotes” is the name of a list.

Reading File in Python-

You can read a text file in Python inside another file. Here, we will discuss some methods to read a file in python.

So to read any file, first, you need to open the file. So to open a file you need to write this code-

data_file=open('files/data.txt')

The first method to read the file is using for Loop-

Method 1-

By using for loop you can read a text file in python. It will print the whole file. Let’s see how to do it-

data_file=open('files/data.txt')
for line in data_file:
   print(line.rstrip())

Here, “rstrip()” is a function to avoid gaps in the lines.

Method 2

Here, the cursor locates at the start, and this method read the lines and store it into the list.

Let’s see in the example-

data_file=open('files/data.txt')
data_file.seek(0)                  # it will locate the cursor at the start
lines=data_file.readlines()
print(lines)

Here, “seek(0)” locates the cursor at the start and “readlines()” read the line and store it into a list.

Method 3-

If you wanna read something fixed in a file, which means you wanna read-only from 50th character to 100th character. Then you can do it by this method.

Let’s see in the example-

data_file=open('files/data.txt')
data_file.seek(50)
file_text=data_file.read(100)
print(file_text)
data_file.close()     # to close the file.

Here, “seek(50)” start reading from the 50th character. And “data_file.read(100)” stop reading at 100th character.

Method 4-

If you don’t wanna close the file after reading, then you can use this method. Here, as you come out from the indentation block, it will automatically close the file.

Let’s see in the example-

def sequence_filter(line):
   return '>' not in line
with open('files/dna.txt') as dna_file:
   lines= dna_file.readlines()
   print(list(filter(sequence_filter,lines)))

Here, “dna_file” is a variable name, where we store our file. This method close the file automatically.

That’s all for the File Handling in Python 3. I hope now you have a better understanding of the File Handling in Python 3.

Congratulations! You successfully learned File Handling in Python 3.

Map, Filter, and Lambda in Python

And Here we go, You Successfully Completed This Tutorial

CONGRATULATIONS TO YOU!

For more interesting articles, keep reading my blogs 🙂

Are you looking for Best Books on Python for Beginners and for Intermediate/Experts?

Check these Books, These Books are the best selling and covered everything in detail.

I hope you will find these Books helpful-

Best Selling Python Books for Beginners

Best Selling Python Books for Intermediates/Experts

All the Best!

Back to Python Tutorial

Thank YOU!

Though of the Day…

“Live as if you were to die tomorrow. Learn as if you were to live forever.” 

Mahatma Gandhi
author image

Written By Aqsa Zafar

Founder of MLTUT, Machine Learning Ph.D. scholar at Dayananda Sagar University. Research on social media depression detection. Create tutorials on ML and data science for diverse applications. Passionate about sharing knowledge through website and social media.

Leave a Comment

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