Python Open Text File and Read Lines

Python File Handling

In Python, at that place is no need for importing external library to read and write files. Python provides an inbuilt office 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 Suspend Text File in Python
  • How to Read Files in Python
  • How to Read a File line past line in Python
  • File Modes in Python

How to Open up a Text File in Python

To open a file, y'all need to use the built-in open part. 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 function

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

Hither,

  • filename: gives name of the file that the file object has opened.
  • mode: attribute of a file object tells you which mode 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, yous tin can create a .text files (guru99.txt) past using the code, we take demonstrated hither:

Step 1) Open the .txt file

f= open("guru99.txt","westward+")
  • We alleged the variable "f" to open a file named guru99.txt. Open up takes two arguments, the file that nosotros want to open and a string that represents the kinds of permission or operation nosotros want to do on the file
  • Hither, we used "due west" letter in our argument, which indicates Python write to file and it will create file in Python if it does not be 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(ten):      f.write("This is line %d\r\n" % (i+i))
  • We accept a for loop that runs over a range of x numbers.
  • Using the write function to enter data into the file.
  • The output we want to iterate in the file is "this is line number", which we declare with Python write file part and then per centum d (displays integer)
  • And then basically nosotros are putting in the line number that nosotros are writing, and so putting it in a railroad vehicle return and a new line character

Pace iii) Shut the file instance

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

Hither is the effect after code execution for create text file in Python instance:

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" it volition expect something like this

How to Create a Text File in Python

Case of how to create a text file in Python


How to Append Text File in Python

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

Step 1)

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

Once again if y'all could meet a plus sign in the code, it indicates that it will create a new file if it does non exist. But in our case we already accept the file, then we are not required to create a new file for Python append to file operation.

Step 2)

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

This will write data into the file in append style.

How to Append Text File in Python

How to Suspend Text File in Python

Y'all tin can meet the output in "guru99.txt" file. The output of the code is that earlier file is appended with new data past Python append to file operation.

Example of How to Append Text File in Python

Example of How to Append Text File in Python

How to Read Files in Python

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

Step i) Open the file in Read mode

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

Step two) We use the mode part in the code to check that the file is in open fashion. If yes, nosotros proceed ahead

if f.mode == 'r':

Pace 3) Use f.read to read file data and store information technology in variable content for reading files in Python

contents =f.read()

Footstep four) Print 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

You can also read your .txt file line by line if your data is also big to read. readlines() code will segregate your data in easy 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 lot run the code (f1=f.readlines()) to read file line past line in Python, it will split each line and present the file in a readable format. In our example the line is brusk and readable, the output will look like to the read mode. But if there is a circuitous data file which is not readable, this piece of code could be useful.

File Modes in Python

Following are the various File Modes in Python:

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

Hither is the complete code for Python impress() to File Instance

Python 2 Example

def primary():      f= open("guru99.txt","w+")      #f=open up("guru99.txt","a+")      for i in range(10):          f.write("This is line %d\r\n" % (i+one))      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 listing      #fl =f.readlines()      #for x in fl:      #print 10 if __name__== "__main__":   chief()

Python 3 Example

Below is another Python print() to File Case:

def primary():     f= open up("guru99.txt","w+")     #f=open("guru99.txt","a+")     for i in range(x):          f.write("This is line %d\r\n" % (i+1))     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 individual line into a listing     #fl =f.readlines()     #for x in fl:     #print(x) if __name__== "__main__":   main()

Summary

  • Python allows y'all to read, write and delete files
  • Utilise the function open("filename","due west+") 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, apply the control open("Filename", "a")
  • Employ the Python read from file function to read the ENTIRE contents of a file
  • Use the readlines role to read the content of the file one past one.

nealyseencesoney.blogspot.com

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

0 Response to "Python Open Text File and Read Lines"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel