Python - Files I/O

Introduction

We have been reading data from the console and publishing it back to the console for user interaction up until now.

More than merely displaying the facts on the console is required. The quantity of data shown on the console may be relatively small due to the volatile nature of memory, making it impossible to restore programmatically created data repeatedly.

When data must be stored in a file permanently, file handling is essential. A file is a designated spot-on disc where related information is kept. The non-volatile information that has been saved can still be accessed after the program has concluded.

The other programming language's file-handling mechanism is simpler or longer than Python.

In Python, files can be saved as text files or binary files. Each file line ends with a distinctive character, whether the file is in text or binary format. As a result, the following procedure can be used to perform a file operation:

  • Open a file
  • Read or write (operate)
  • Close the file

Opening a file

The file name & the access mode to be utilized to open the file are the two arguments that Python's open () Method accepts. The function returns a file object that could be utilized for writing, reading, and various other operations.

Syntax:

file object = open(<file-name>, <access-mode>, <buffering>)    

The files could be accessed in many ways, including reading, writing, and adding. The access mode for opening a file is described in the next section.

S.NoAccess ModeDescription
1.rOpened in read-only mode, the file. At the start, the file pointer is present. The file is opened in this way automatically if no access mode is specified.
2.rbIt opens the binary file in read-only mode. The file's beginning contains the file pointer.
3.r+The file is open for both reading and writing. The file's beginning contains the file pointer.
4.rb+The binary file is opened in both writing and reading. The file's beginning contains the file pointer.
5.WThe file is only opened for writing. If a file with the same name already exists, it generates a new one. If not, it replaces it. The file pointer is located at the start of the file.
6.wbIt opens the file so that it can only accept binary data as input. If the file already exists, it is replaced; otherwise, a new one is created. The file's beginning contains the file pointer.
7.W+Both reading and writing are permitted in the file. It differs from r+ in that it replaces any previously written files instead of r+, which leaves them alone. If a file doesn't already exist, it creates one. The file's beginning contains the file pointer.
8.Wb+The file is accessible for reading and writing. The file's beginning contains the file pointer.
9.aThe file is opened in append mode. The file pointer is located there if a previous file has been written. If no file with an identical name exists, it creates a new one.
10abIn binary format, it opens the file in append mode. The pointer can be found at the file's end that was previously written. It generates a binary file with that name if none already exists.
11.a+A file is opened for reading and appending. If the file already exists, the file pointer stays at the end of the file. If no file with an identical name exists, it creates a new one.
12.ab+A file in binary format is opened for reading and adding. The file pointer is still present at the file's end.

In this simple example, we'll open the file "file.txt" in a read-only state and output its contents to the console. The same directory contains this file.

Example:

#opens the file file.txt in read mode   

fileptr = open("file1.txt","r")

if fileptr:   

print("file is opened successfully")

Output:

Python - Files I/O

The first argument in the code above was filename, and the second option, r, was used to open the file under read-only mode. If the file is opened successfully, the print statement will be executed by the fileptr, which houses the file object.

close () Method:

Once all operations have been completed, the file must be closed using our Python script's close () Method. Any unwritten data is erased once a file object uses the close () Method.

It is best practice to close the file once all actions have been completed because we can execute any operation on it by utilizing the file system that Python is now open to.

The close () Method's syntax is provided below.

Syntax:

fileobject.close()   

Consider the case below.

# opens the file file.txt in read mode    

fileptr = open("file1.txt","r")    

if fileptr:    

   print("file is opened successfully")    

            #closes the opened file    

fileptr.close()

We are unable to open the file again after it is closed. It's essential to close the file completely. The program ends without closing the file if an exception arises while executing some operations on the file.

We should apply the subsequent strategy to solve this issue.

try:  

fileptr = open("file.txt")  

# perform file operations  

finally:  

fileptr.close()

The with statement:

Python 2.5 saw the introduction of the with the statement. When manipulating files, the with statement is helpful. It is utilized when a code block between statements must be performed.

The following is the syntax to use when opening a file with the statement.

with open (<file name>, <access mode>) as <file-pointer>:    

#statement suite

With statements have the advantage of ensuring file closure regardless of how the nested block exits.

The with statement is always recommended when dealing with files since it immediately closes the file when a break, return, or exception happens in a nested block of code; we don't need to create the close () function. It prevents the file from being corrupt.

Consider the case below.

Example:

With open("file.txt",'r') as f:

content = f.read();    

print(content)

Writing the file:

The file must first be opened utilizing the open Method and one of the following access modes before any text can be entered.

If a file already exists, it will overwrite it. The file's beginning contains the file pointer.

The present file will be supplemented with a new one. The file's end contains the file pointer. If a file doesn't already exist, it creates one.

Consider the case below.

Example:

# open the file.txt in append mode. Create a new file if no such file exists. 

fileptr = open("file1.txt", "w") 

# appending the content to the file 

fileptr.write('''''Python is the modern day language. It makes things so simple.

It is the fastest-growing programing language''')

# closing the opened the file 

fileptr.close()

#open the existing file

fileptr=open("file1.txt","r")

print(fileptr.read())

Output:

Python - Files I/O

Snapshot of the file1.txt

Python - Files I/O

Reading the file:

The read () function in Python reads a file using a script. The file is read to produce a string by the read () Method. Both text data and binary data can be read by it.

The syntax for the read () Method is listed below.

fileobj.read(<count>)    

In this case, the count refers to the number of bytes that must be read at the file's beginning. The file's contents may be read if the count isn't supplied.

Consider the case below.

Example:

#open the file.txt in read mode. This causes the error if no such file exists.   

fileptr = open("file1.txt","r") 

#stores all the data of the file into the variable content   

content = fileptr.read(11)  

# prints the type of data stored in the file   

print(type(content))     

#prints the content of the file   

print(content)      

#closes the opened file   

fileptr.close()

Output:

Python - Files I/O

In the code above, we have read the contents of file1.txt using the read () function. The first ten characters of the file will be read because we passed the count value of ten.

The next line will print the file's contents if utilized.

fileptr=open("file1.txt","r")

content = fileptr.read() 

print(content)

Output:

Python - Files I/O

Read file through for loop:

The file can be read using a for loop.

Example:

#open the file.txt in read mode. This causes an error if no such file exists.   

fileptr = open("file1.txt","r");    

#running a for loop    

for i in fileptr:   

    print(i) # i contains each line of the file

Output:

Python - Files I/O

Read Lines of the file:

Python's readline() function makes reading a file line by line easy. The readline() Method reads the file's lines starting at the beginning, and thus if we use it twice, we will get the file's first two lines.

Consider the example below, which uses the readline() function to read the initial line of the three-line file "file1.txt" in our example. Consider the case below.

Example 1:

Twice, two lines from the file were read using the readline() function.

#open the file.txt in read mode. This causes an error if no such file exists.   

fileptr = open("file1.txt","r");    

#stores all the file data into the variable content   

content = fileptr.readline()     

content1 = fileptr.readline() 

#prints the content of the file   

print(content)    

print(content1) 

#closes the opened file   

fileptr.close()

Output:

Python - Files I/O

The readline() function was used twice, pulling two lines from the file.

The readlines() function is one that Python offers that is used to read lines. The number of lines until the file's end (EOF) is returned.

Example 2:

Using the readlines() Method, reading lines.

#open the file.txt in read mode. This causes an error if no such file exists.   

fileptr = open("file1.txt","r");    

#stores all the data of the file into the variable content   

content = fileptr.readlines()    

#prints the content of the file   

print(content)    

#closes the opened file

fileptr.close()

Output:

Python - Files I/O

Conclusion:

After we learned about files, input, and output (I/O) operations were conducted. The file performs the following operations: open, read, write, & close.