Python 3 Read File Line by Line

Python Read File Line by Line

In Python, you can read all the lines in a file using different methods. These include readlines (), readline () and context managers. You can read all the text in the files subsequently opening them and perform other operations.

  1. readlines (): read all lines in a file at once
  2. readline () with for loop
  3. readline () with while loop
  4. Context managers

1. Readlines (): Read All Lines in a File at Once

The readlines () method is the about popular method for reading all the lines of the file at once. This method reads the file until EOF (Terminate of file), which means it reads from the offset line until the concluding line.  When y'all apply this method on a file to read its lines, it returns a list. This listing contains all the lines of the file. Here, each line within the list is a listing object.

The syntax of the method is as follows:

file.readlines (num_line)

Here, the num_line parameter specifies the number of lines or number of bytes that have to be read from the file. But this parameter is optional. It takes an integer value. If the returned bytes exceed the number specified in the hint, the method will stop returning lines. The default value for this method is -i, which means all the lines inside the file will be returned.

For example,

          # Python iii Code # Python Program to read file line by line  # Open file mf = open("myfile.txt", "r+") print("File to read: ", mf.name)  # Read all lines in the file file_content = mf.readlines()  # Print all lines in file impress("Read Line: ", file_content)  # Close opened file mf.close()        

Output:

          File to read:  myfile.txt Read Line:  ['Line 1\northward', 'Line two\n', 'Line three\due north', 'Line 4\n', 'Line five']        

The readlines () method is a very good choice for reading all the contents of a small file. But y'all might face problems while working with large files.

Python read file line by line

two. Using "While" Statement

Now we volition look at how you tin can read the lines of a file ane past one using a while statement. If you are working with a large file with a lot of text, it is best to use the readline () method. This method fetches the lines one by ane instead of retrieving all the text at i get.

Instance,

          # Python 3 Code # Python Plan to read file line by line # Using while statement  # Open file mf = open up("myfile.txt", "r+") print("File to read: ", mf.proper noun)  # Read single line in file file_line = mf.readline()  # use the readline() method to read further. # If the file is not empty keep reading one line # at a fourth dimension, till the file is empty  while file_line:     impress(file_line)     # utilise realine() to read next line     file_line = mf.readline()  # Close opened file mf.shut()        

Output:

          Line one Line two Line iii Line iv Line v        

Another instance of the while statement is:

          # Python 3 Code # Python Program to read file line by line # Using while statement  # Open up file mf = open("myfile.txt", "r+") impress("File to read: ", mf.name)  while True:     # Read unmarried line in file     file_line = mf.readline()     print(file_line)     if not file_line:         break  # Close opened file mf.close()        

Output:

          Line one Line two Line 3 Line four Line 5        

In the in a higher place lawmaking, the while statement checks for a Boolean value to exist True. The readline () method reads the text line by line. When it reaches the end of the file, the execution of the while loop stops.

3. Using "for" Loop

You can read the lines of a file in Python using a for loop. Apply the following code for it:

          # Python iii Code # Python Programme to read file line past line # Using while statement  # Open file mf = open("myfile.txt", "r+") print("File to read: ", mf.proper name)  for file_line in mf:     # Impress single line     print(file_line)  # Close opened file mf.close()        

Output:

          Line one Line ii Line iii Line four Line v        

Here, mf is the file handler that is used for opening the file called myfile.txt. A for loop is executed on every line in the text file. file_line  the variable used for iterating through the loop.

iv. Using Context Manager

If y'all are opening a file for some performance, you demand to close it as well. In instance you lot don't close it, information technology volition automatically be closed when the function yous are using to handle it completes execution. This happens when the final reference of the file handler is destroyed. Only at that place may exist a situation where the programs are long and the function volition not complete execution soon.

In that case, you have to brand employ of a context managing director in Python. This manager will perform all the tasks such as closing files for yous - fifty-fifty if you forget to practise it.

Have a look at this program,

          # Python 3 Code # Python Programme to read file line by line # Using Context Manager List_file_lines = ["Apple tree", "Orange", "Banana", "Mango"]  # Ascertain role to create file def create_file():     with open ("testfile.txt", "w") equally wf:         for line in List_file_lines:             # Write all lines             wf.write(line)             wf.write("\n")  # Ascertain function to read files def read_File():     rf = open ("testfile.txt", "r")      # Read file lines     out = [] # list to save lines     with open ("testfile.txt", "r") as rf:         # Read lines using for loop         for line in rf:             # All lines and strip final line which is newline             out.append(line.strip())     return out  # Define principal function to create and read file def main():          # Create test file     create_file()          # Read lines from testfile.txt     outList = read_File()          # Iterate over the lines     for line in outList:         print(line.strip())      # Run postal service function  if __name__ == "__main__":     main()        

Output:

          Apple Orangish Banana Mango        

Here the with clause depicts the concept of context managers. This keeps rail when you are opening the file and closes information technology as soon as the part ends.
Some other example of context managers forth with a while loop is equally follows:

          # Python 3 Code # Python programme to read file line by line # Using context manager & while Loop  with open ("myfile.txt", "r") as rf:     # Read each line of a file in the loop     for line in rf:         # Impress every line in a file except the last line which is newline \n         print(line.strip())                  

Output:

          Line one Line two Line three Line four Line five        

Decision

The method you volition employ for reading the lines of a file will depend upon the type of file y'all have. If you have a small file with a few lines of text, readlines () method is the all-time way to get. Using a for loop is also good for pocket-sized files. For larger files, this method is not very memory efficient. Then, in that case, you tin can use the while statement along with with the readline () method.

Context managers will brand sure that you lot tin read all lines of a file without worrying about closing the file handler.

parkeronewarthill46.blogspot.com

Source: https://www.stechies.com/read-file-line-by-line-python/

0 Response to "Python 3 Read File Line by Line"

ارسال یک نظر

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel