A Complete Guide To Reading And Writing Files In Python

Hello guys, to get the most value of this article, please play with the given code in this article.you can’t master just by reading this article. right?

I promise you that If you read and practice the whole article thoroughly, you can write code easily for reading and writing files in python

Introduction

In any programming language, we generally need to do many file handling operations.

For every high-level programming language, there will be a pre-built open() function.The main objectives of this function are read, write, append (end of the line) etc.

Let’s know how this open() function will exactly work to achieve the above objectives.

Basically, when we execute an open() function, it acts like a Python object.As we know that, every object has some methods and attributes, we have some attributes or modes in the Python open() function.

We are going to do many file handling operations (reading and writing files in python ) by using these modes in Python.Okay, I will tell you about these modes soon 🙂

What You Need To Know About the File Types:

A file can be anything whether it is an executable, image and document etc.Python just considers them or put them into two categories, those are:

Text file

Binary file

Simply, A text file has some group of characters or sequences of lines where those are terminated by an (EOL) mostly ‘,’ or ‘/’.These are helpful to make an interpreter to start a new line or terminating the file.

Now, another one binary file is that which is not a text file simply it can be an image file.

Python has the ability to read, write or create binary files with its pre-built functions and attributes.

Introduction To Open() Function Syntax

As I said before, Every object has its own attributes.So, We need to give some arguments while read, write or access the file object in python.

If you observe the below pic shows us what arguments can be given for open function those are:

file

mode

buffering

encoding

errors

newline

closefd

opener

But except file and mode arguments we don’t bother much about other arguments and they will take none as default values

In the below code, I created an object called file with two arguments only called filename and mode.Leave remaining and let them take the default values.

#creating file object with two arguments filenametype and modefile=open("filename","mode")

Modes

The mode argument will help us in which way a file can be accessed.These are the available modes:

Mode

Function

r

To read files – file should be created already

w

To write files – to create and write content to the files – Will erase the previous data

a

Appending to an existing file – end of the line (previous data will not be deleted )

r+

If you want to perform both the actions (read and write) then this will be useful

Note: If you want to read and append the files then we have to use a+

How To Create A Text File

I assumed that now you have some idea about the file, file types, and modes in Python.Let’s get started and create our own file.

file=open("firstFile.txt","w")
file.write("Hello world \n")
file.write("This is my first file")
file.close()

In the above code, I created a text file called firstFile.txt with a “w” (write) mode.Now in the next two lines, we are writing some text to that file.

Then we are going to close it.Now run the program so that we should have the firstFile.txt file in the same directory where the code is being presented.

How To Read A Text File In Python

In the above section, we have created a file and wrote some lines to it.In this section, we are going to print/read those lines on Python console.For Python read operations, replace the mode with “r”.

read() Usage

file=open("firstFile.txt","r")
print(file.read())
file.close()

Here, the read() function used to read all the data presented in a certain file.And, the print function is going to print that data to console.

read(n) Usage

file=open("firstFile.txt","r")
print(file.read(17))
file.close()

we can use the read(n) function to read specific length of characters(including spaces).In the above example, I have given that, this code should read up-to 17 characters only.So Here is the output.

readline() Usage

In the above examples, We have read all the data in a file and up to the specific length of characters.What If you would like to read them line by line so that it doesn’t look like messy.

file=open("firstFile.txt","r")
print(file.readline())
file.close()

The above file printed only the first line of the text file what if you want to print the next file.We will see that in the next section.

readline(n) Usage

file=open("firstFile.txt","r")
print(file.readline(2))
file.close()

The above code will be going to read and print the second line of the file.We can give certain line numbers as per our wish.

In these two examples we have read the single line by giving the line number but what If we have to read all the lines at a time will be discussed in the next section.

readlines() Usage

file=open("firstFile.txt","r")
print(file.readlines())
file.close()

The above code would return the Python List of all the lines in that text file.

output: ['Hello world \n', 'This is my first file']
If we want to print all the elements in the above list we need to iterate through it.Please refer the below code.

file=open("firstFile.txt","r")
lines =file.readlines()
for line in lines:
print(line)
file.close()

Output

Hello world
This is my first file

How To Use With Statement in python file handling operations

There is another way to create and handle files in Python programming language.Unlike, above method, we are not going to use any assignment operator here.

write operation using with statement

withopen('firstFile.txt', 'w') as f:
f.write('This is python write operation using with statement')
f.close()

Here, We didn’t use any assignment operator.Instead, we are using with and as.And, everything will remain as same as above sections.

Read Operation Using With Statement

withopen('firstFile.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line)
f.close()