How to Read Contents of a File in Python

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

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

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

What is the open() office in Python?

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

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"), so you lot can simply reference the file name in the open() role.

                open("demo.txt")              

Here is an example of both files beingness 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 demand to reference the correct path proper noun for the text file.

In this case, the random-text file is inside a different binder then master.py:

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

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

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

If you don't have the right path for the file, and so y'all will get 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 then you can reference the correct path proper name.

Optional Style parameter in open()

At that place are dissimilar modes when y'all are working with files. The default way is the read manner.

The letter of the alphabet r stands for read mode.

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

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

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

There are other types of modes such every bit "westward" for writing or "a" for appending.  I am not going to get into particular for the other modes considering we are just going to focus on reading files.

For a complete listing of the other modes, delight read through the documentation.

Boosted parameters for the open up() function in Python

The open() part 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 want to bank check if a file can exist read, then you lot tin use the readable() method. This will return a True or False.

This case would render True considering nosotros are in the read way:

                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) manner, then 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 as one string. This is a expert method to use if yous 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") impress(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, only a portion of information technology will be read.

If we modify the earlier case, we can impress out merely the first word by adding the number four as an statement for read().

                file = open("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 volition be read.

What is the close() method in Python?

Once you are done reading a file, it is important that you close it. If y'all forget to close your file, and so that can crusade issues.

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

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

How to use the with keyword to close files in Python

One way to ensure that your file is closed is to apply the with keyword. This is considered good practice, because the file volition 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 render that.

In this example, we have a text file with these ii sentences:

                This is the showtime line This is the second line              

If nosotros utilise the readline() method, it will simply print the offset sentence of the file.

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

This method besides takes in the optional size parameter. Nosotros tin modify the example to add the number 7 to only 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 return a list of all of the lines in the file.

In this example, nosotros are going to impress out our grocery items equally 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 exist to use a for loop.

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

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

Conclusion

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

                open("proper name of file y'all desire opened", "optional mode")                              

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

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

The open up() part takes in the optional way parameter. The default mode is the read style.

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

If yous want to check if a file can be read, and so you can employ the readable() method. This will render a True or Imitation.

                file.readable()              

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

                file.read()              

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

                file.close()              

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

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

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

                file.readline()              

The readlines() method volition read and render a list 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:         impress(detail)              

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



Larn to code for free. freeCodeCamp'southward open source curriculum has helped more than twoscore,000 people get jobs as developers. Become started

heilmanmility.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 Contents of a File in Python"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel