Read a Line From a Text File Python
In Python, there are a few means you lot tin can read a text file.
In this article, I will go over the open()
function, 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, you lot showtime have to open it.
This is the basic syntax for Python's open()
function:
open("proper noun of file you desire opened", "optional mode")
File names and correct paths
If the text file and your current file are in the same directory ("folder"), then you can just reference the file name in the open up()
function.
open("demo.txt")
Hither is an example of both files being in the same directory:
If your text file is in a unlike directory, then you volition demand to reference the correct path proper noun for the text file.
In this example, the random-text
file is inside a different folder and then main.py
:
In order to access that file in the primary.py
, y'all 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 right path for the file, then yous will become an mistake bulletin similar this:
open("random-text.txt")
Information technology is really important to continue track of which directory you are in so you can reference the correct path name.
Optional Mode parameter in open()
At that place are different modes when you are working with files. The default mode is the read style.
The letter r
stands for read mode.
open up("demo.txt", mode="r")
You can besides omit mode=
and only write "r"
.
open up("demo.txt", "r")
There are other types of modes such as "west"
for writing or "a"
for appending. I am not going to go into item for the other modes because we are simply going to focus on reading files.
For a complete list of the other modes, please read through the documentation.
Boosted parameters for the open()
function in Python
The open()
role 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 cheque if a file can be read, then yous can use the readable()
method. This volition return a True
or False
.
This example would return True
because nosotros are in the read mode:
file = open("demo.txt") print(file.readable())
If I changed this example, to "westward"
(write) mode, then the readable()
method would return Faux
:
file = open("demo.txt", "w") impress(file.readable())
What is the read() method in Python?
The read()
method is going to read all of the content of the file as one cord. This is a good method to utilise if y'all don't take 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())
This method can take in an optional parameter called size. Instead of reading the whole file, merely a portion of it will exist read.
If we modify the earlier example, we can print out only the first word by calculation the number 4 every bit an argument for read()
.
file = open up("demo.txt") impress(file.read(4))
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 lot are done reading a file, it is important that you close it. If you 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") impress(file.read()) file.close()
How to utilize the with
keyword to close files in Python
One way to ensure that your file is closed is to use the with
keyword. This is considered good do, because the file will close automatically instead of you having to manually close it.
Here is how to rewrite our case 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 i line from the file and return that.
In this example, 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 impress the first sentence of the file.
with open("demo.txt") equally file: print(file.readline())
This method besides takes in the optional size parameter. We can modify the example to add together the number seven to merely read and print out This is
:
with open up("demo.txt") as file: print(file.readline(seven))
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 print out our grocery items equally a list using the readlines()
method.
with open("demo.txt") as file: impress(file.readlines())
How to use a for loop to read lines from a file in Python
An alternative to these dissimilar read methods would be to utilise 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("demo.txt") equally file: for particular in file: print(item)
Conclusion
If you want to read a text file in Python, y'all offset have to open information technology.
open("name of file you want opened", "optional mode")
If the text file and your current file are in the aforementioned directory ("folder"), then you tin can just reference the file name in the open()
function.
If your text file is in a unlike directory, and then you will need to reference the right path name for the text file.
The open()
function takes in the optional fashion parameter. The default mode is the read mode.
open("demo.txt", "r")
If y'all want to cheque if a file can exist read, and so you 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 ane string.
file.read()
Once y'all are done reading a file, information technology is important that yous close it. If you lot forget to close your file, then that can cause issues.
file.shut()
One way to ensure that your file is airtight is to utilize the with
keyword.
with open up("demo.txt") as file: impress(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 different read methods would be to use a for loop
.
with open("demo.txt") every bit file: for item in file: print(item)
I hope you enjoyed this commodity and best of luck on your Python journey.
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Go started
Source: https://www.freecodecamp.org/news/python-open-file-how-to-read-a-text-file-line-by-line/