Files in Python

In this class, We discuss Files in Python.

For Complete YouTube Video: Click Here

The reader should have prior knowledge of class and object concepts. Click here.

Based on the assumption the reader knows class and object, This session is explained.

In this session, we discuss text files. There are binary files used for image, audio, video, etc.

We discuss binary files in our later classes.

Files in python

Open a File

Given below is the text file created in our system. The file name is Test.txt

Hello, This is our first file.

Take an example and understand how to read the files and the different options available.

Below is the example program we consider.

# Files
# By default it will be read mode

f = open("test.txt",'r') # open a file 
print(f.read())     # read the entire file
                    #file pointer moved to last
print(f.read())



Output:
This is our first file

To read the file, we use the function ‘open.’

In the function ‘open,’ we gave the file name. By default, the open function will be in reading mode.

The open function will read the data in the file and create a file object.

The open function returns the file object.

The reference to the file object is given to the variable f.

Point to understand: Now, we can use the methods available in file class.

In our example, we used the read method to read the entire file.

Point to understand: Python maintains a file pointer. This pointer shows the position in the file.

Once we read the file, the file pointer is at the end of the file.

If we reread the file, the read method starts reading from the file pointer position at the end of the file.

In our example, we used the read method twice. The second time it is not displaying any content.

Take one more example to understand the concept better.

f = open("test.txt",'r')# open a file 
print(f.read(7))     # read the first seven characters
                     #file pointer moved to 7th position
print(f.read(4))
print(f.read())

Output:
This is
 our
 first file

In the example, we are reading the seven characters. The file pointer will be at the eighth character.

Again we read the following four characters. Python starts reading the 8,9,10, and 11 characters.

Now the file pointer is at the twelfth character. This is how the file pointer is used.

Close the File

Once we open the file. We need to close the file after our work is done.

After closing the file, we can not access the file anymore.

We use the close method to close the file.

Below the example, I am showing the close method on the file.

# File close

f = open("test.txt")# open a file 
print(f.read())     # read the entire file
f.close()
print(f.read()) # file is not opened

Output:
ValueError: I/O operation on closed file.

In the above example, we got an error. Because after closing the file, we are trying to reread the file.

Write Mode

By default, files are in reading mode.

We can change the option to write mode.

The below example shows how to change the file to write mode.

# File in Write mode
f = open("test.txt",'w')# open a file 
f.write("we are writting new content")
f.write("\n another content continuation")
f.close()
f = open("test.txt",'r')# open a file 
print(f.read())
f.close()

Output:
we are writting new content
 another content continuation

We use the option ‘w’ to open the file in write mode.

To write something to the file. The file should be in write mode.

The method ‘write’ is used to write the new content to the file.

In the above example, we used the write method the first time.

The write method deletes the previous content and places the new data because the file pointer is at the begining of the file.

The second time we used the write method, The file pointer is at the location after writing the first data.

So it is continuing to write data from the file pointer location.

If we want to write the new content without losing the old content, we should open the file in append mode.

Append Mode

We use the option ‘a’ to open the file in append mode.

The below example shows how to append the new content to the existing data.

# file in append mode
f = open("test.txt",'a')# open a file 
f.write("\nwe are appending new content")
f.write("\n another content continuation")
f.close()
f = open("test.txt",'r')# open a file 
print(f.read())
f.close()

Output:
we are writting new content
 another content continuation
we are appending new content
 another content continuation

Read Write Mode and Seek Method

To open the file in read-write mode, we use the option ‘r+’.

The seek method is used to move the file pointer to the index location needed.

The below example shows the use of the method ‘seek’ to move to index position 0. i.e., the start of the file.

#file in read write mode
f = open("test.txt",'r+')# open a file 
oldcontent=f.read()
f.seek(0)
f.write("hello \n how are you\n"+oldcontent)
f.seek(0)
print(f.read())
f.close()

Output:
hello 
 how are you
we are writting new content
 another content continuation
we are appending new content
 another content continuation

In the above example, we are taking the existing content to the variable ‘old content.

After we are using seek a method to move the file pointer to zero indexes.

We are writing the new content and adding old content after the new content.

Truncate Method

The truncate method is used to resize the file to the given number of bytes.

The below example shows the use of the truncate method.

#file in read write mode truncate use
f = open("test.txt",'r+')# open a file 
f.truncate(6)
f.seek(0)
print(f.read())
f.close()

Output:
hello 

f = open("test.txt",'r+')# open a file 
f.truncate(2)
f.seek(0)
print(f.read())
f.close()

Output:
he

In the above example, we are reading the file, and we are truncating to 6 bytes.

From the file, six characters will be present, and the remaining are truncated. I.e., deleted.

When we read the data after truncate, it is displaying only hello.

The below example shows truncate the file to two bytes.

The number of bytes is optional.

Suppose the number of bytes is not given. The truncate method takes the current position.