Read the Lines of an Open Text File Python Again

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

In Python, there are a few ways you lot can read a text file.

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

What is the open() part in Python?

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

This is the basic syntax for Python's open() office:

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

File names and right paths

If the text file and your current file are in the aforementioned directory ("binder"), then you lot tin just reference the file name in the open() function.

                open("demo.txt")              

Here is an case 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 lot will need to reference the correct path name for the text file.

In this instance, the random-text file is inside a dissimilar folder and so main.py:

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

In guild to admission that file in the main.py, you have to include the binder 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 you will go an error message like this:

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

It is really of import to keep rail of which directory y'all are in and so you tin reference the correct path name.

Optional Mode parameter in open()

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

The letter r stands for read mode.

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

Yous can also omit mode= and but write "r".

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

There are other types of modes such as "w" for writing or "a" for appending.  I am not going to go into particular for the other modes because we are merely going to focus on reading files.

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

Additional parameters for the open() role in Python

The open() role tin accept in these optional parameters.

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

To larn more than near these optional parameters, please read through the documentation.

What is the readable() method in Python?

If you want to check if a file tin can be read, then you can employ the readable() method. This volition render a Truthful or Fake.

This case would return True because we are in the read way:

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

If I changed this example, to "w" (write) mode, and so the readable() method would return False:

                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 practiced method to use if you don't have a lot of content in the text file.

In this instance, 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 have in an optional parameter called size. Instead of reading the whole file, merely a portion of it will be read.

If we modify the earlier instance, nosotros tin can print out only the first discussion by calculation the number 4 as an argument for read().

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

If the size argument is omitted, or if the number is negative, and so the whole file volition be read.

What is the close() method in Python?

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

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

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

How to apply the with keyword to shut files in Python

One way to ensure that your file is airtight is to use the with keyword. This is considered good practice, because the file will close 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:     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 example, we have a text file with these two sentences:

                This is the first line This is the second line              

If we use the readline() method, it will only print the start sentence of the file.

                with open("demo.txt") as 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 alter the case to add the number seven to merely read and print out This is:

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

In this instance, we are going to print 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 employ a for loop to read lines from a file in Python

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

In this example, we can print out all of the items in the demo.txt file past looping over the object.

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

Conclusion

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

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

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

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

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

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

If you want to check if a file can be read, then you tin use the readable() method. This volition return a True or False.

                file.readable()              

The read() method is going to read all of the content of the file as ane string.

                file.read()              

Once yous are done reading a file, it is important that you shut it. If you forget to close your file, and so that tin can cause issues.

                file.close()              

I 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 i line from the file and return that.

                file.readline()              

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

                file.readlines()              

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

                with open("demo.txt") as file:     for item in file:         impress(particular)              

I hope you enjoyed this article and all-time of luck on your Python journeying.



Larn to lawmaking for free. freeCodeCamp'south open source curriculum has helped more than than forty,000 people get jobs as developers. Go started

simmonsrancelf.blogspot.com

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

0 Response to "Read the Lines of an Open Text File Python Again"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel