Python Read in a Las File Line by Line

Python Open File – How to Read a Text File Line by Line

In Python, there are a few means y'all can read a text file.

In this article, I will go over the open up() function, the read(), readline(), readlines(), close() methods, and the with keyword.

What is the open up() function in Python?

If you lot want to read a text file in Python, y'all first have to open up information technology.

This is the basic syntax for Python'due south open() function:

                open("name of file you want opened", "optional mode")              

File names and correct paths

If the text file and your current file are in the same directory ("folder"), then you lot can merely reference the file proper name in the open() function.

                open up("demo.txt")              

Hither is an example of both files being in the same directory:

Screen-Shot-2021-09-13-at-1.49.16-AM

If your text file is in a unlike directory, then yous will demand to reference the correct path proper noun for the text file.

In this example, the random-text file is within a dissimilar folder then principal.py:

Screen-Shot-2021-09-13-at-2.00.27-AM

In social club to access that file in the main.py, you have to include the folder proper name with the proper noun of the file.

                open("text-files/random-text.txt")              

If you lot don't have the correct path for the file, and then you will get an mistake message like this:

                open up("random-text.txt")              
Screen-Shot-2021-09-13-at-2.03.33-AM

It is really important to keep track of which directory you are in and so yous can reference the right path proper name.

Optional Mode parameter in open()

There are unlike modes when you are working with files. The default manner is the read mode.

The letter of the alphabet r stands for read mode.

                open("demo.txt", fashion="r")              

You tin can also omit way= and just write "r".

                open("demo.txt", "r")              

There are other types of modes such equally "w" for writing or "a" for appending.  I am non going to go into detail for the other modes because we are just going to focus on reading files.

For a complete list of the other modes, please read through the documentation.

Additional parameters for the open() office in Python

The open up() office can take in these optional parameters.

  • buffering
  • encoding
  • errors
  • newline
  • closefd
  • opener

To learn more well-nigh these optional parameters, delight read through the documentation.

What is the readable() method in Python?

If you desire to check if a file tin exist read, then y'all tin can utilize the readable() method. This will return a True or False.

This instance would return Truthful because nosotros are in the read style:

                file = open("demo.txt") impress(file.readable())              
Screen-Shot-2021-09-13-at-3.36.37-AM

If I inverse this example, to "w" (write) way, then the readable() method would return False:

                file = open("demo.txt", "westward") impress(file.readable())              
Screen-Shot-2021-09-13-at-3.36.18-AM

What is the read() method in Python?

The read() method is going to read all of the content of the file every bit i string. This is a good method to use if you don't have a lot of content in the text file.

In this example, I am using the read() method to print out a list of names from the demo.txt file:

                file = open("demo.txt") print(file.read())              
Screen-Shot-2021-09-13-at-2.43.59-AM

This method tin can take in an optional parameter called size. Instead of reading the whole file, only a portion of it will be read.

If nosotros modify the earlier example, we can print out only the first word by calculation the number 4 equally an argument for read().

                file = open up("demo.txt") print(file.read(4))              
Screen-Shot-2021-09-13-at-3.01.30-AM

If the size statement is omitted, or if the number is negative, then the whole file will be read.

What is the close() method in Python?

Once you are done reading a file, information technology is of import that you shut information technology. If you forget to close your file, and so that tin can crusade bug.

This is an instance of how to shut the demo.txt file:

                file = open("demo.txt") print(file.read()) file.close()              

How to use the with keyword to close files in Python

1 manner to ensure that your file is closed is to use the with keyword. This is considered skillful practise, considering the file will shut automatically instead of you having to manually close information technology.

Here is how to rewrite our example using the with keyword:

                with open("demo.txt") as file:     print(file.read())              

What is the readline() method in Python?

This method is going to read one line from the file and render that.

In this example, we take a text file with these two sentences:

                This is the offset line This is the second line              

If nosotros use the readline() method, information technology will but print the get-go sentence of the file.

                with open("demo.txt") equally file:     print(file.readline())              
Screen-Shot-2021-09-13-at-3.57.14-AM

This method as well takes in the optional size parameter. We can modify the example to add the number 7 to only read and print out This is:

                with open up("demo.txt") as file:     print(file.readline(7))              
Screen-Shot-2021-09-13-at-4.08.03-AM

What is the readlines() method in Python?

This method will read and return a list of all of the lines in the file.

In this case, we are going to impress out our grocery items as a list using the readlines() method.

                with open("demo.txt") as file:     impress(file.readlines())              
Screen-Shot-2021-09-13-at-4.19.23-AM

How to use a for loop to read lines from a file in Python

An alternative to these different read methods would be to utilize a for loop.

In this instance, we can impress out all of the items in the demo.txt file by looping over the object.

                with open("demo.txt") equally file:     for item in file:         print(item)              
Screen-Shot-2021-09-13-at-4.27.49-AM

Conclusion

If yous desire to read a text file in Python, you lot first have to open it.

                open("proper name of file you want opened", "optional mode")                              

If the text file and your current file are in the same directory ("folder"), then you lot can just reference the file name in the open() function.

If your text file is in a different directory, and then you lot will need to reference the correct path proper noun for the text file.

The open() role takes in the optional mode parameter. The default manner is the read mode.

                open up("demo.txt", "r")              

If yous want to bank check if a file can be read, and so you tin use the readable() method. This will return a True or False.

                file.readable()              

The read() method is going to read all of the content of the file as one cord.

                file.read()              

Once you are done reading a file, it is important that you shut it. If y'all forget to close your file, then that can cause bug.

                file.shut()              

One way to ensure that your file is closed is to utilize the with keyword.

                with open up("demo.txt") as file:     print(file.read())              

The readline() method is going to read one line from the file and return that.

                file.readline()              

The readlines() method will read and render a listing of all of the lines in the file.

                file.readlines()              

An alternative to these different read methods would exist to utilise a for loop.

                with open("demo.txt") equally file:     for particular in file:         print(detail)              

I hope you enjoyed this commodity and best of luck on your Python journey.



Learn to lawmaking for free. freeCodeCamp's open source curriculum has helped more than than 40,000 people get jobs as developers. Get started

spriggsbeenests.blogspot.com

Source: https://www.freecodecamp.org/news/python-open-file-how-to-read-a-text-file-line-by-line/

0 Response to "Python Read in a Las File Line by Line"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel