Skip to content Skip to sidebar Skip to footer

How to Read File Backwards in Python

Python File Handling

In Python, there is no demand for importing external library to read and write files. Python provides an inbuilt function for creating, writing, and reading files.

In this file handling in Python tutorial, we will larn:

  • How to Open a Text File in Python
  • How to Create a Text File in Python
  • How to Suspend Text File in Python
  • How to Read Files in Python
  • How to Read a File line by line in Python
  • File Modes in Python

How to Open a Text File in Python

To open a file, you need to utilize the built-in open function. The Python file open function returns a file object that contains methods and attributes to perform various operations for opening files in Python.

Syntax of Python open up file role

file_object  = open up("filename", "mode")

Here,

  • filename: gives name of the file that the file object has opened.
  • mode: attribute of a file object tells you which fashion a file was opened in.

More details of these modes are explained below

How to Create a Text File in Python

With Write to file Python, y'all can create a .text files (guru99.txt) by using the code, we have demonstrated here:

Step ane) Open the .txt file

f= open("guru99.txt","west+")
  • We declared the variable "f" to open a file named guru99.txt. Open takes two arguments, the file that we desire to open and a string that represents the kinds of permission or operation we desire to practice on the file
  • Here, we used "w" alphabetic character in our statement, which indicates Python write to file and it will create file in Python if it does non be in library
  • Plus sign indicates both read and write for Python create file operation.

Footstep ii) Enter data into the file

for i in range(x):      f.write("This is line %d\r\n" % (i+ane))
  • We take a for loop that runs over a range of ten numbers.
  • Using the write function to enter data into the file.
  • The output nosotros want to iterate in the file is "this is line number", which we declare with Python write file role and then percentage d (displays integer)
  • Then basically nosotros are putting in the line number that we are writing, then putting it in a carriage render and a new line character

Stride three) Shut the file instance

f.shut()
  • This will shut the instance of the file guru99.txt stored

Here is the result after code execution for create text file in Python example:

How to Create a Text File in Python

How to Create a Text File in Python

When you click on your text file in our case "guru99.txt" information technology volition look something like this

How to Create a Text File in Python

Example of how to create a text file in Python


How to Suspend Text File in Python

You can also suspend/add together a new text to the already existing file or a new file.

Step i)

f=open("guru99.txt", "a+")

Once again if you could come across a plus sign in the code, it indicates that it will create a new file if it does not exist. But in our case we already accept the file, so we are not required to create a new file for Python append to file performance.

Step 2)

for i in range(2):      f.write("Appended line %d\r\n" % (i+1))

This will write data into the file in append fashion.

How to Append Text File in Python

How to Append Text File in Python

You can see the output in "guru99.txt" file. The output of the code is that earlier file is appended with new data by Python suspend to file operation.

Example of How to Append Text File in Python

Case of How to Append Text File in Python

How to Read Files in Python

You tin read a file in Python by calling .txt file in a "read mode"(r).

Step 1) Open the file in Read mode

f=open("guru99.txt", "r")

Stride 2) We use the mode function in the lawmaking to cheque that the file is in open up mode. If yep, nosotros keep alee

if f.mode == 'r':

Step three) Use f.read to read file information and shop information technology in variable content for reading files in Python

contents =f.read()

Pace 4) Print contents for Python read text file

Hither is the output of the read file Python instance:

How to Read Files in Python

How to Read Files in Python


How to Read a File line by line in Python

You tin also read your .txt file line past line if your information is also big to read. readlines() code will segregate your data in easy to read mode.

How to Read a File line by line in Python

How to Read a File line past line in Python

When you run the code (f1=f.readlines()) to read file line by line in Python, information technology will divide each line and present the file in a readable format. In our case the line is short and readable, the output will expect similar to the read way. Simply if there is a complex data file which is not readable, this piece of code could be useful.

File Modes in Python

Following are the diverse File Modes in Python:

Way Description
'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing.
If file does non exist, information technology creates a new file.
If file exists it truncates the file.
'10' Creates a new file. If file already exists, the operation fails.
'a' Open file in append mode.
If file does not exist, it creates a new file.
't' This is the default mode. Information technology opens in text mode.
'b' This opens in binary way.
'+' This volition open a file for reading and writing (updating)

Hither is the complete code for Python print() to File Example

Python 2 Example

def main():      f= open("guru99.txt","w+")      #f=open("guru99.txt","a+")      for i in range(10):          f.write("This is line %d\r\n" % (i+i))      f.close()         #Open the file dorsum and read the contents      #f=open("guru99.txt", "r")      #   if f.manner == 'r':       #     contents =f.read()      #     print contents      #or, readlines reads the individual line into a list      #fl =f.readlines()      #for x in fl:      #print x if __name__== "__main__":   main()

Python 3 Instance

Below is another Python print() to File Example:

def main():     f= open("guru99.txt","w+")     #f=open("guru99.txt","a+")     for i in range(ten):          f.write("This is line %d\r\north" % (i+ane))     f.close()     #Open the file back and read the contents     #f=open("guru99.txt", "r")     #if f.manner == 'r':     #   contents =f.read()     #    print (contents)     #or, readlines reads the individual line into a list     #fl =f.readlines()     #for 10 in fl:     #print(x) if __name__== "__main__":   main()

Summary

  • Python allows you to read, write and delete files
  • Utilise the part open("filename","w+") for Python create text file. The + tells the python interpreter for Python open text file with read and write permissions.
  • To append data to an existing file or Python print to file performance, use the command open("Filename", "a")
  • Use the Python read from file function to read the Entire contents of a file
  • Use the readlines function to read the content of the file one by one.

robinsoncarecter.blogspot.com

Source: https://www.guru99.com/reading-and-writing-files-in-python.html

Post a Comment for "How to Read File Backwards in Python"