Python Program Read File Line by Line

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

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

In this commodity, I volition go over the open() function, the read(), readline(), readlines(), shut() methods, and the with keyword.

What is the open() part in Python?

If you want to read a text file in Python, you first have to open information technology.

This is the basic syntax for Python's 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"), and then y'all can just reference the file name in the open up() 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 different directory, then you will need to reference the correct path proper name for the text file.

In this instance, the random-text file is inside a different folder then main.py:

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

In order to access that file in the main.py, yous have to include the binder proper name with the name of the file.

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

If you don't have the correct path for the file, then y'all will get an mistake message similar 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 you tin can reference the correct path name.

Optional Mode parameter in open()

There are different modes when you are working with files. The default fashion is the read mode.

The letter r stands for read fashion.

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

You can also omit mode= and only write "r".

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

In that location are other types of modes such equally "w" for writing or "a" for appending.  I am non going to become into detail for the other modes considering we are simply going to focus on reading files.

For a consummate listing of the other modes, please read through the documentation.

Boosted parameters for the open() function in Python

The open up() function tin take in these optional parameters.

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

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

What is the readable() method in Python?

If you desire to check if a file can be read, so you tin use the readable() method. This will return a Truthful or False.

This example would return True because we are in the read mode:

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

If I changed this example, to "w" (write) manner, then the readable() method would return Imitation:

                file = open("demo.txt", "w") print(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 one string. This is a proficient method to use if yous don't take 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 up("demo.txt") print(file.read())              
Screen-Shot-2021-09-13-at-2.43.59-AM

This method can accept in an optional parameter called size. Instead of reading the whole file, only a portion of it volition exist read.

If nosotros alter the earlier instance, nosotros tin can print out only the first word by adding the number 4 as an argument for read().

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

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

What is the shut() method in Python?

Once you are done reading a file, it is important that you lot close it. If yous forget to close your file, then that tin can crusade issues.

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

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

How to use the with keyword to shut files in Python

One style to ensure that your file is closed is to use the with keyword. This is considered expert practice, because the file volition shut automatically instead of y'all having to manually close information technology.

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

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

What is the readline() method in Python?

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

In this instance, we have a text file with these 2 sentences:

                This is the get-go line This is the second line              

If we utilize the readline() method, information technology will only print the commencement sentence of the file.

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

This method also takes in the optional size parameter. Nosotros can modify the example to add the number 7 to merely read and print out This is:

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

What is the readlines() method in Python?

This method will read and render 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:     print(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 culling to these different read methods would exist to utilize a for loop.

In this example, we can print 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:         impress(item)              
Screen-Shot-2021-09-13-at-4.27.49-AM

Conclusion

If you want to read a text file in Python, you offset take to open up information technology.

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

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

If your text file is in a different directory, then you will demand to reference the correct path name for the text file.

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

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

If you want to bank check if a file can exist read, so y'all can 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 string.

                file.read()              

One time you are done reading a file, it is important that yous shut information technology. If y'all forget to shut your file, then that tin cause issues.

                file.close()              

1 manner to ensure that your file is closed is to use the with keyword.

                with open up("demo.txt") every bit 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 return a list of all of the lines in the file.

                file.readlines()              

An alternative to these unlike read methods would exist to use a for loop.

                with open("demo.txt") as file:     for item in file:         print(detail)              

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



Larn to code for gratuitous. freeCodeCamp's open up source curriculum has helped more than than 40,000 people get jobs every bit developers. Become started

gallaherexprion1962.blogspot.com

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

Belum ada Komentar untuk "Python Program Read File Line by Line"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel