Python 3 Reading 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. Yous can read all the text in the files after 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

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

The readlines () method is the most popular method for reading all the lines of the file at once. This method reads the file until EOF (Stop of file), which ways information technology reads from the get-go line until the last line.  When you apply this method on a file to read its lines, it returns a list. This list contains all the lines of the file. Hither, each line inside the list is a listing object.

The syntax of the method is equally follows:

file.readlines (num_line)

Here, the num_line parameter specifies the number of lines or number of bytes that accept to be read from the file. Merely this parameter is optional. Information technology 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 -1, which means all the lines within the file will exist returned.

For example,

          # Python 3 Code # Python Plan to read file line by line  # Open up 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 print("Read Line: ", file_content)  # Close opened file mf.shut()        

Output:

          File to read:  myfile.txt Read Line:  ['Line one\northward', 'Line two\n', 'Line three\n', 'Line four\northward', 'Line five']        

The readlines () method is a very expert selection for reading all the contents of a small file. Simply you might face up problems while working with big files.

Python read file line by line

2. Using "While" Argument

At present we will look at how yous can read the lines of a file i past one using a while statement. If you are working with a big file with a lot of text, it is best to utilise the readline () method. This method fetches the lines one past i instead of retrieving all the text at i get.

Example,

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

Output:

          Line ane Line two Line three Line four Line 5        

Another case of the while statement is:

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

Output:

          Line i Line 2 Line iii Line four Line five        

In the higher up code, the while statement checks for a Boolean value to be True. The readline () method reads the text line by line. When it reaches the terminate of the file, the execution of the while loop stops.

3. Using "for" Loop

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

          # Python 3 Code # Python Program to read file line by line # Using while statement  # Open up file mf = open("myfile.txt", "r+") print("File to read: ", mf.proper noun)  for file_line in mf:     # Print single line     print(file_line)  # Shut opened file mf.shut()        

Output:

          Line 1 Line ii Line three 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.

four. Using Context Manager

If you are opening a file for some functioning, you need to shut information technology too. In case you don't close it, it will automatically be closed when the part you are using to handle information technology completes execution. This happens when the last reference of the file handler is destroyed. But there may be a situation where the programs are long and the office will non complete execution presently.

In that instance, you have to make use of a context manager in Python. This managing director will perform all the tasks such as closing files for you - even if you lot forget to exercise it.

Take a look at this program,

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

Output:

          Apple tree Orange Banana Mango        

Hither the with clause depicts the concept of context managers. This keeps rail when you are opening the file and closes it as before long as the function ends.
Some other example of context managers along with a while loop is equally follows:

          # Python three Code # Python programme to read file line past 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 \due north         print(line.strip())                  

Output:

          Line one Line 2 Line iii Line iv Line five        

Decision

The method you will use for reading the lines of a file will depend upon the type of file you have. If you have a pocket-size file with a few lines of text, readlines () method is the best way to get. Using a for loop is also good for small files. For larger files, this method is not very retentiveness efficient. So, in that example, you can use the while statement forth with with the readline () method.

Context managers volition make certain that yous can read all lines of a file without worrying about closing the file handler.

steinloven1957.blogspot.com

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

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel