File operation In Python – File Handling

In this Python article, we will discuss the complete detail of file handling in python like how to create, open, read, write, and append a file along with certain examples and bonus points. Let’s get started.

1. What is I/O in files?

Input/output operation on files includes some specific things like opening a file, read from the file, write into the file, close the file along with certain methods. Collectively it makes the I/O in files. Now the question may arise in mind that how can we make a file in python. Hence first, let’s understand what is files.

File handling in Python

2. What is a file and why do we need file in Python?

Any information or data which stays in the computer storage devices is known as a file. We already know there are different kinds of files, like music files, video files, text files etc. Python gives easy ways to manipulate these files.

Generally, we divide files into two categories, text file, and binary file. Text files are simple text whereas binary files contain binary data which is only readable by a computer.

The main use of files is to store the information in any non-volatile memory source such as a hard disk, pen drive, SSDs, etc.

While working, the data remains in the RAM which is volatile in nature meaning that data will be lost as soon as the computer turns off. Hence, there is a need for making a file to store the data permanently, whichever is needed.

Before reading or writing from a file, the file must be open and after the operation is being performed, the file must be closed for the computer to release the acquired resources.

Now, when we know what is files, let’s understand how python handles the files and their various operations.

2.1. File object Characteristics in Python

After opening a file, we can use different objects related to the file which will display all information contained in the file or relevant details about the file.

S.N.CharacteristicSpecification
1file.closedIf the file is closed then it will return true, otherwise false otherwise.
2file.modeIt gives the access mode used to open the file.
3file.nameIt gives the file name
4file.softspaceIf explicit space is required then it will print false, otherwise true
Table for file objects

3. How does Input/ Output works in Python?

In python, to display the output we have the simplest command available, name as print, which has been used from the starting of the tutorial series.

As we know, print takes input in brackets where we can pass variables by using commas. Print treats every statement inside it as a string and prints it as output.

3.1. Types of Input from the Keyboard

In python, we have only two functions( built-in) that help in reading lines through a standard input, which has been given using the keyboard. These functions are −

  • raw_input – This function returns the input by reading the first line and removes all trailing next lines.
  • input – This function is similar to the raw_input function but it estimates the input provided to be valid and returns the computed result.

However, the above difference is applicable for python 2.X as python 3.X only has the input function, it was renamed in the earlier updates.

# An example for input
str = input("Enter your input\n\t: ")
print "Received input is : ", str
Output
Enter your input
    : dcv
Received input is :  dcv

4. What is file Handling in Python?

In the development of any web application, file handling plays a vital role. Many functions come pre-installed in Python like creating a file, updating a file, reading a file, and deleting a file.

In python, the primary objective of file handling is to read the files and write the files and apply certain operations on files. Many programming languages support file handling which is more or less complex and large. But python has extensive, short, and easy concepts.

In python, every file is considered either as text or binary which is quite an interesting point to notice. Every code line has a character sequence which ultimately forms a file.

EOL denotes that the line of the file has ended and it is terminated using a special character such as comma {,} or newline character. EOL tells the interpreter to start a new line as the existing line is terminated.

4.1. Different modes for opening a file

In general, python has four methods to open a file. The four different methods are:

  • a – stands for Append – This keyword opens the file for appending anything. If the file does not exist then it creates a new one.
  • r – stands for Read – This keyword opens the file for reading. If the file is not present in the system, an error will be given.
  • w – stands for Write – This keyword opens the file for writing. It can create a non-existing file.
  • x – stands for Create – This keyword is used to create the respective file. If the file is already in existence, then it will return an error.

Apart from these four methods above, we can choose whether we want to handle the file in a binary mode or text mode.

  • t – stands for Text – This keyword loads the default values in text format.
  • b – stands for Binary – This keyword loads the data in binary mode (like loading an image)
Syntax:
file_1 = open("savefile.txt", "rt")
or
file_1 = open("savefile.txt", "r")   # By default text mode
Modes keywordSpecification
rUse to open and read a file
wUse to open and write a file for writing. A new file will be created if it does not exist.
xUse to open and apply exclusive creating. If the file exists, the task fails.
aOpens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist.
tUse to open a file in text mode
bUse to open a file in binary mode.
+Use to open file for editing purpose
Tabular form of modes explanation

5. How to open a file in python?

In python, to open a file, we simply use the open() built-in function. As soon as we call the function, an object file is assigned as an output known as a handle for modification purposes.

Two arguments are passed into the open() function which accepts the file name along with the mode of the file. Hence, the syntax becomes open(nameof file, modeofthefile). We can also specify the buffering value.

Buffering − Buffering occurs when it is set to value 1 and is performed only while the file is being accessed. If the value is set to 0, buffering will not happen.

We can specify the value of the buffer and the buffer will accommodate its size. If we specify a negative value, the default value will be set into the buffer.

Note: The file on which we want to perform operations can be anywhere in the system, but if the file is not in the same directory as that of the program then we have to use the fully qualified name or the relative path.

file_1 = open('xyz.txt', 'r')

for i in file_1:    #reading line one by one
    print (i)
Output
c
co
cod
codi
codin
coding
codinge
codingee
codingeek
wow! Great place reached.

The output is based on the text file data, it may vary from user to user and mode to mode.


6. How to close files in Python?

After finished with the operations on the file, the file must be closed. All the resources allocated to the file will be released once we close it. We close the file with the help of  close() keyword.

In python, we have a garbage collector which deletes objects which are unreferenced but relying on it for closing the file is not a good decision. However, this method does not ensure full safety. If an exception occurs while performing certain operation with any file, file does not close but the code exits.

file_1 = open('xyz.txt', 'r')
file_1.close() 

The safest way is using try and finally block. let’s see how.

file_1 = open('xyz.txt', 'r')
try:
   file_1 = open("test.txt", encoding = 'utf-8')
   # perform file operations
finally:
   file_1.close()

7. How to read files in Python?

As we discussed above, we can use the r keyword to open the file. However, there are different ways to read a file.

By using we can extract a string that contains all characters in the file. Let’s take a look at a short example:

file_1 = open('xyz.txt', 'r')

print (file.read(11)) #reading the 11 characters 
print (file.read(6)) #read next 6 characters - ends with a space
print (file.read()) #read rest of the file
print (file.read()) # gives empty string
Output
Codingeek -
a home 
for developers

The current file cursor can be moved with the help of the seek() method and the tell() method is used to return to the current position of cursor in file.

file_1 = open('xyz.txt', 'r')

print(file_1.tell())    
print(file_1.seek(4))
print(file_1.tell())  
Output
0
4
4

If we want the program to read lines individually, then we can do so with the help the readline() method. This enables includes the new line character while reading the file. Let’s have a look.

file_1 = open('xyz.txt','r')
print(file_1.readline())
print(file_1.readline())
print(file_1.readline())
Output
Codingeek.com
Home for Coders
Knowledge is power

8. How to write on a file using Python?

To write on a file, we use write() method. It writes the provided string in the mentioned file. In the string, we may pass binary data as well as the text.

with open('xyz.txt', 'w', encoding = 'utf-8') as f:
  f.write("Codingeek.com\n")
  f.write("Home for Coders")

f = open('xyz.txt','r')  #checking
print(f.read())
Output
Codingeek.com
Home for Coders

9. How to append to a file using Python?

Appending is almosst similar to writing to a fil, wehave to simply use a mode to open the file and then all the data that we write will be added to the end of the existing data.

Lets assume we have a file with data “Codingeek.com” in it.

with open('xyz.txt', 'a') as f:
  f.write("\nKnowledge is power")
  
f = open('xyz.txt','r')      #checking
print(f.read())
Output
Codingeek.com
Knowledge is power

10. How can we rename & remove the file using python?

The python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.

To use this module you need to import it first and then you can call any related functions.

We can change the name of a file using rename() method. It accepts two arguments, the name of the current file and the name of the new file.

Syntax:
import os 
os.rename(r'file path\OLD file name with ext',r'file path\NEW file name with ext')

To remove a specific file, we use remove() method. It intakes the name of the file to be deleted as its argument.

Syntax:
os.remove(file_name)

11. How to Split word files using file handling?

In python, we can split each line of a file using the split method on files. It will split the variable when blank space will occur.

# Python code to illustrate split() function
with open("xyz.txt", "r") as f:
  lines = f.readlines()
  for eachline in lines:
      char = eachline.split()
      print (char)
Output
['Codingeek.com']
['Home', 'for', 'Coders']
['Knowledge', 'is', 'power']

12. Conclusion

In this article we learned about

  • What is I/O in files in python.
  • What is a file and why do we need a file in Python along with File object characteristics
  • How does Input/ Output work in Python and also the types of Input from the Keyboard
  • What is file Handling and Different modes for opening a file
  • How to open a file in python, close files in Python, read files in Python, and write on a file using Python?
  • How to append a file using python?
  • How can we rename & remove the file using python?
  • How to Split word files using file handling?

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index