How to Read an Open File in Python

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

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

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

What is the open() function in Python?

If you want to read a text file in Python, you lot starting time have to open up it.

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

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

File names and correct paths

If the text file and your electric current file are in the aforementioned directory ("binder"), and so you can just reference the file name in the open() function.

                open("demo.txt")              

Hither 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 dissimilar directory, then you will need to reference the right path name for the text file.

In this example, the random-text file is within a different binder then main.py:

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

In society to access that file in the chief.py, yous have to include the folder proper name with the proper noun of the file.

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

If you don't accept the right path for the file, then you lot will get an error message similar this:

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

It is actually important to keep track of which directory you are in so you tin reference the correct path name.

Optional Style parameter in open()

There are different modes when y'all are working with files. The default style is the read mode.

The letter r stands for read mode.

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

You lot can also omit mode= and just write "r".

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

At that place are other types of modes such every bit "w" for writing or "a" for appending.  I am not going to go into detail for the other modes because we are just going to focus on reading files.

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

Additional parameters for the open() function in Python

The open() function can take in these optional parameters.

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

To learn more about these optional parameters, please read through the documentation.

What is the readable() method in Python?

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

This instance would render Truthful because nosotros are in the read manner:

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

If I changed this example, to "w" (write) mode, 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 equally one string. This is a good method to employ if you don't have a lot of content in the text file.

In this example, I am using the read() method to impress 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 can have in an optional parameter called size. Instead of reading the whole file, only a portion of it volition exist read.

If we change the earlier example, we tin can impress out only the first word past calculation the number 4 as an statement for read().

                file = open up("demo.txt") print(file.read(iv))              
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, it is important that y'all close information technology. If yous forget to close your file, then that can cause issues.

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

                file = open up("demo.txt") impress(file.read()) file.close()              

How to employ the with keyword to shut files in Python

I fashion to ensure that your file is airtight is to employ the with keyword. This is considered good practise, because the file volition close automatically instead of you having to manually shut it.

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

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

                This is the beginning line This is the second line              

If we use the readline() method, it will only print the first 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 as well takes in the optional size parameter. We can change the instance to add the number 7 to only read and impress 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 example, we are going to print out our grocery items as a listing 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 exist to use a for loop.

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

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

Decision

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

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

If the text file and your current file are in the same directory ("folder"), so y'all tin can merely reference the file name in the open() function.

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

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

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

If you want to check if a file can exist read, so yous can use the readable() method. This will render a True or Fake.

                file.readable()              

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

                file.read()              

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

                file.close()              

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

                with open("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 volition read and return a listing of all of the lines in the file.

                file.readlines()              

An culling to these different read methods would be to employ a for loop.

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

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



Acquire to code for gratis. freeCodeCamp'due south open up source curriculum has helped more 40,000 people become jobs as developers. Get started

lininteall38.blogspot.com

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

0 Response to "How to Read an Open File in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel