In this article we are going to learn about file handling in python. How to open a file using python, Different python methods to Read and write a content in a file. Close the file once we are done with the editing. Also we are going to see other methods available in python read/write mode.

File handling in python:

So before getting started with the topic file handling in python. Let’s first try to understand what is a file?

Term “file” is very basic concept for a computer user. File is a container which is used to store the information on permanent storage (like Hard disc drive). These files later can be accessed by different computer programs. A unique name and path given to the files is used by human users, computer programs and scripts to access a file for reading and modification purposes.

File Handling in python includes three basic operations. Opening, Reading, writing, appending data into it and then closing the file.
File Handling in python.

As a normal computer user we know how to open, read and write a file. However here in this article we are learning file handling in context of python or python I/O operations it includes following three main operations.

  1. Open a file or create new file.
  2. Read/Write, append data into a file.
  3. Close the file.

To read or write the data in a file, Firstly we need to open it. Read or write the data in it and once we are done with the reading or writing the data we have to close the file. So that the resources which are engaged with these operation are released.

So let’s go with the each of the operation.


How to open file in python?

  • To open a file using python there is a built-in open() function available. This function returns a file object (also known as handle) which can be used for reading or writing the file accordingly.
  • Python open() function requires two important input parameters to open a file.
    1. File name (Along with its full path if the specified file is not present in same directory.).
    2. Mode (Type of operation we want to perform like read, write etc. and also mode in which we want to open a file).

Python syntax to open a file:

Syntax for opening a file in python:
<file_object> = open("File name", mode, encoding)
Test_handle = open("sample.txt", "r") # Without full path since file is present in working directory.
Test_handle = open("C:\\temp\\sample.txt", "r") # With full path specified.

If we want to open a file from the location other than the working directory in that case we need to specify the full path of file. Otherwise if we want to open a file which is present in our working directory then just specifying the name of file is sufficient.

Python modes for opening a file:

There are basic four modes of opening a file.

ModeDescription
"r"Read: This is the default mode of opening a file. It opens the file in read only mode.
"w"Write: This mode opens the file for writing. This mode erases all the existing data in file and over-writes the new data on it. If the provided file does not exist then it creates a new file.
"a"Append: It opens the file and appends the new input data at the end of existing data.
"x"Create: Exclusive create mode will create a new file with the specified name.

In addition to the above mentioned modes, You can also specify how the file should be handled.

ModeDescription
"t"Text: This is the default mode and it opens the file in text mode. This mode is preferred while dealing with text files.
"b"Binary: This mode opens the file in Binary mode. It is preferred while handling the non text files such as images or exe files.

When a file is opened in text mode it returns us a string whereas on the other hand if the file is opened in Binary mode it returns us bytes.

Python default file opening mode:

Now we know what is meant by modes, But what will happen if we don’t specify the mode while opening a file in python?

So the answer is, if we don’t specify the mode then it will take the default values i.e ‘rt‘ since “r: Read” and ”t: Text” are the default modes of file opening in python. Therefore both the lines written in below example are same and they will open the file (Sample.txt) in reading and text mode.

file_object = open("Sample.txt")
file_object = open("Sample.txt" 'rt')

Python encoding mode while opening a file.

While working with different platform like windows and Linux. If we open a same file in text mode without specifying the encoding details there are chances that it may behave differently. It happens since encoding is platform dependent. On windows encoding is “cp1252” while on Linux it is “UTF-8”.

Therefore while opening a file in text mode it is highly recommended that we should specify the encoding mode as well.

file_object = open("Sample.txt", mode='rt', encoding='UTF-8')

How to create a new file using python?

We can create a new file using python using following two ways;

  • In python open() method specify the mode “x” (Exclusive create). This mode will create a new file with specified name at working directory or at specified path.
  • In python open() method specify the mode “w” (Write). This mode will create a new file with specified name at working directory or at specified path. Also it will open the newly created file in writing mode.
# Python program to create a file and write a text data into it.

write_handle = open("C:\\temp\\sample1.txt", 'w') # File name along with full path specified.
write_handle.write("I am able to create new file using python.\n")
write_handle.write("Also I can write a text in file using python.")

#Output:
I am able to create new file using python.\n
Also I can write a text in file using python.

How to Read a file using python?

Read mode is used when we just want to read the content of file and not to edit it.

To read the selective data from a file we must specify the “size” parameter. If read(size) parameter is not provided then all the content of file till its end will be read and returned.

#Python program to read a text file content.
Read_handle = open("C:\\temp\\sample1.txt") #size parameter is not specified.
print(Read_handle.read())

#Output:
I am able to create new file using python.\n
Also I can write a text in file using python.

# Python program to read selective content from file i.e with size argument.
Test_handle = open("C:\\temp\\sample1.txt")
print(Test_handle.read(10))

# Output:

I am able

#Get the current cursor position.
print(Test_handle.tell())
# Output:
10

#Bring back the cursor to required position.
Test_handle.seek(5)
print(Test_handle.tell())
# Output:
5

While reading a file we can also find the current cursor position and also get it back to the initial position using following python methods.

  • tell(): This method returns the current cursor position.
  • seek(): This python method brings the cursor back to the initial position.
#Python syntax to handle the cursor position.
file_object.tell() # It tells us the current cursor position.
file_object.seek() # This python method will bring back the cursor to the initial position.
#Open a file sample1.txt
Test_handle = open("C:\\temp\\sample1.txt")
print(Test_handle.read(10))
#Output:
I am able

#Python program to get the cursor position.
print(Test_handle.tell())
#Output:
10

#Python program to get the cursor to the specified position.
Test_handle.seek(5)
print(Test_handle.tell())
#Output:
5

To read the complete file line by line is possible using following few methods.

  • for loop: It is used to read complete file till its end. This python file reading method is fast and efficient.
  • readline(): This python file reading method is used to read individual lines of a file. This method reads a file till the newline, including the newline character as well.
#Python program to read a file using for loop.
file_object = open("C:\\Temp\\sample1.txt", 'r')
for line in file_object:
print(line, end = '');

#Output:
am able to create new file using python.\n
Also I can write a text in file using python.

#Python code to read an individual line from file using readline() method.
print(file_object.readline())

#Output:
am able to create new file using python.\n

How to write into a file using python?

Till now we have learned about how to open a file in python. Now we want to write into the file using python.

  • So for writing a data into a file a basic requirement is that, we should have the file opened in either of the following mode i.e write (w), append (a) or exclusive creation (x).
  • Also one thing to always keep in mind that, We should be careful while opening a file in write (w) mode since it over-writes the new data on the existing one. So all the existing data present in the file will be erased.

For writing into a file there is built-in python write() method available. Let’s see one sample python program to create new text file and write few text lines into it.

#Python program for creating a text file and writing text data into it.
file_object = open("C:\\Temp\\sample.txt", "x")
file_object.write("First python file writing program.\n")
file_object.write("I can write text in file using python write function.\n")

file_object.close()
New_file_object1 = open("C:\\Temp\\sample.txt", "r")
print(New_file_object1.readline())

#Output:
First python file writing program.

Above program will create a new sample.txt and it will write following two lines “First python file writing program” and “I can write text in file using python write function.” into the newly created
sample.txt file.

If the file sample.txt is already available at the same location then it will show us an error. “\n” newline characters given at the end of each sentence will write the sentence on new line.

How to append the data into a file using python:

If we are having a file with some existing data into it, Now we want to add some new data in same file without loosing the existing data. In that case we can use python append mode for file opening.

Basic difference between python write and append mode is that, When we open a file with “w” (write) mode then all the existing data from the file is erased and new data is written over it. Whereas if we open a file with “a” append mode then it will not erase the existing data. Also whatever new data we are going to write will be added at the end of existing data.

For demo purpose let’s use our existing text file (sample.txt) and append some new text into it.

#Python program to append text into a file.
file_object = open("C:\\Temp\\sample.txt", 'a')
file_object.write("Newly appended text using python.")
file_object.close() #Close the file after appending the text into it.

New_file_object1 = open("C:\\Temp\\sample.txt", "r")
print(New_file_object1.readlines())

#Output:
First python file writing program.\n I can write text in file using python write function.\n Newly appended text using python.

How to close a file using python.

Now we know how to open, Read, write and append the data into a file using python. The last step we should always do is to close the file once we are done with our required operations.

Closing a file is important in python file handling since it will free up the resources engaged with opening, reading and writing a file. Python close() is the built-in method available to close a file properly.

One thing to note here is once we close the file using file_handle.close() method then later if we try to perform any operations using file handle will show us an error.

In above sample program “#Python program to append text into a file.” we have used file_handle.close() method to close the sample.txt file.

Continue Learning:

Also you can get more help on python forum.  Click Here

Share this Post

Leave a Comment

Your email address will not be published.