How to Read the Text File in Python

Python File Handling

In Python, in that location is no need for importing external library to read and write files. Python provides an inbuilt function for creating, writing, and reading files.

In this file treatment in Python tutorial, we will learn:

  • How to Open a Text File in Python
  • How to Create a Text File in Python
  • How to Append 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, yous demand to use the congenital-in open function. The Python file open up 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 function

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

Here,

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

More details of these modes are explained beneath

How to Create a Text File in Python

With Write to file Python, you lot can create a .text files (guru99.txt) by using the lawmaking, we have demonstrated hither:

Step one) Open the .txt file

f= open("guru99.txt","w+")
  • We declared the variable "f" to open a file named guru99.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or performance we want to practise on the file
  • Hither, nosotros used "w" letter in our argument, which indicates Python write to file and it will create file in Python if information technology does not exist in library
  • Plus sign indicates both read and write for Python create file operation.

Step ii) Enter information into the file

for i in range(10):      f.write("This is line %d\r\due north" % (i+ane))
  • Nosotros take a for loop that runs over a range of 10 numbers.
  • Using the write function to enter information into the file.
  • The output we want to iterate in the file is "this is line number", which we declare with Python write file role and and then percent d (displays integer)
  • And so basically we are putting in the line number that we are writing, then putting it in a carriage return and a new line graphic symbol

Footstep 3) Close the file case

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

Here is the result later on 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 example "guru99.txt" it will look something like this

How to Create a Text File in Python

Instance of how to create a text file in Python


How to Suspend Text File in Python

You lot tin likewise append/add a new text to the already existing file or a new file.

Step 1)

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

Once again if yous could see a plus sign in the code, information technology indicates that it will create a new file if information technology does not be. But in our case we already have the file, so we are non required to create a new file for Python suspend to file operation.

Step 2)

for i in range(two):      f.write("Appended line %d\r\due north" % (i+one))

This will write data into the file in append mode.

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 before file is appended with new data by Python suspend to file operation.

Example of How to Append Text File in Python

Example of How to Suspend Text File in Python

How to Read Files in Python

Yous can read a file in Python by calling .txt file in a "read mode"(r).

Step 1) Open the file in Read mode

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

Step 2) We employ the mode function in the code to cheque that the file is in open mode. If yes, we proceed ahead

if f.mode == 'r':

Step 3) Apply f.read to read file data and store it in variable content for reading files in Python

contents =f.read()

Step 4) Impress contents for Python read text file

Here is the output of the read file Python example:

How to Read Files in Python

How to Read Files in Python


How to Read a File line by line in Python

Y'all can also read your .txt file line past line if your data is too big to read. readlines() code volition segregate your data in piece of cake to read style.

How to Read a File line by line in Python

How to Read a File line by line in Python

When you run the lawmaking (f1=f.readlines()) to read file line by line in Python, it will separate each line and present the file in a readable format. In our case the line is short and readable, the output will look similar to the read style. But if at that place is a complex data file which is not readable, this piece of lawmaking could be useful.

File Modes in Python

Post-obit are the diverse File Modes in Python:

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

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

Python ii Example

def primary():      f= open("guru99.txt","west+")      #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.mode == 'r':       #     contents =f.read()      #     print contents      #or, readlines reads the private line into a listing      #fl =f.readlines()      #for x in fl:      #impress x if __name__== "__main__":   main()

Python 3 Case

Below is another Python print() to File 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+1))     f.close()     #Open the file back and read the contents     #f=open("guru99.txt", "r")     #if f.mode == 'r':     #   contents =f.read()     #    print (contents)     #or, readlines reads the individual line into a list     #fl =f.readlines()     #for x in fl:     #print(ten) if __name__== "__main__":   chief()

Summary

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

gagnerrappy1960.blogspot.com

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

0 Response to "How to Read the Text File in Python"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel