Write Python Program to Read Values From Text File
To read a text file in Python:
- Open the file.
- Read the lines from the file.
- Close the file.
For case, let's read a text file called example.txt from the same folder of the lawmaking file:
with open('example.txt') every bit file: lines = file.readlines()
Now the lines variable stores all the lines from instance.txt as a list of strings.
This is the quick reply. To learn more details about reading files in Python, please read along.
Reading Text Files in Python
Reading a text file into your Python program follows this procedure:
- Open the file with the congenital-in open() function by specifying the path of the file into the telephone call.
- Read the text from the file using ane of these methods: read(), readline(), readlines().
- Close the file using the close() method. You lot tin allow Python handle endmost the file automatically past opening the file using the with argument.
ane. How to Apply the open up() Role in Python
The bones syntax for calling the open() part is:
open up(path_to_a_file, manner)
Where:
- path_to_a_file is the path to the file you lot desire to open. For example Desktop/Python/example.txt. If your python program file is in the same folder every bit the text file, the path is merely the name of the file.
- mode specifies in which state you want to open up the file. There are multiple options. But as you're interested in reading a file, you only need the mode 'r'.
The open() function returns an iterable file object with which you can easily read the contents of the file.
For instance, if you have a file chosen case.txt in the aforementioned folder as your code file, you can open it by:
file = open up("case.txt", "r")
Now the file is opened, just not used in any useful way even so.
Adjacent, let'southward take a look at how to actually read the opened file in Python.
2. File Reading Methods in Python
To read an opened file, let's focus on the 3 different text reading methods: read(), readline(), and readlines():
- read() reads all the text from a file into a unmarried cord and returns the string.
- readline() reads the file line by line and returns each line as a separate string.
- readlines() reads the file line by line and returns the whole file equally a list of strings, where each cord is a line from the file.
Later you are going to run into examples of each of these methods.
For example, let's read the contents of a file called "example.txt" to a variable as a string:
file = open("example.txt") contents = file.read()
Now the contents variable has whatsoever is within the file equally a single long cord.
3. E'er Shut the File in Python
In Python, an opened file remains open equally long as you don't close information technology. And then make certain to close the file after using information technology. This tin exist done with the close() method. This is important because the program can crash or the file can corrupt if left hanging open.
file.close()
You tin can also let Python take intendance of closing the file by using the with statement when dealing with files. In this case, you don't need the shut() method at all.
The with statement structure looks like this:
with open(path_to_file) as file: #read the file here
Using the with statement is so convenient and conventional, that we are going to stick with it for the balance of the guide.
Now y'all understand the basics of reading files in Python. Side by side, let's have a look at reading files in activity using the dissimilar reading functions.
Using the File Reading Methods in Python
To repeat the following examples, create a folder that has the following 2 files:
- A reader.py file for reading text files.
- An example.txt file from where your program reads the text.
Besides, write some text on multiple lines into the example.txt file.
The read() method in Python
To read a file to a single string, utilise the read() method. As discussed above, this reads any is in the file as a single long string into your plan.
For example, let's read and print out the contents of the case.txt file:
with open up("instance.txt") equally file: contents = file.read() print(contents)
Running this piece of code displays the contents of example.txt in the console:
Hi This is just an instance I demonstrate reading lines
The readline() Method in Python
To read a file one line at a time, employ the readline() method. This reads the electric current line in the opened file and moves the line pointer to the next line. To read the whole file, use a while loop to read each line and move the file pointer until the cease of the file is reached.
For example:
with open up('example.txt') equally file: next_line = file.readline() while next_line: impress(next_line) next_line = file.readline()
Every bit a result, this program prints out the lines i by i as the while loop proceeds:
Hi This is but an instance I'm demonstrate reading lines
The readlines() Method in Python
To read all the lines of a file into a list of strings, utilise the readlines() method.
When you take read the lines, you can loop through the listing of lines and print them out for example:
with open('example.txt') as file: lines = file.readlines() line_num = 0 for line in lines: line_num += ane print(f"line {line_num}: {line}")
This displays each line in the console:
line i: Hello line 2: This is simply an example line 3: I'm demonstrate reading lines
Utilize a For Loop to Read an Opened File
You lot just learned near iii different methods yous can use to read a file into your Python programme.
It is good to realize that the open() function returns an iterable object. This means that y'all tin can loop through an opened file just like you would loop through a list in Python.
For instance:
with open('instance.txt') as file: for line in file: print(line)
Output:
Howdy This is just an case I'm demonstrate reading lines
As you can see, yous did not demand to employ whatsoever of the congenital-in file reading methods. Instead, you used a for loop to run through the file line by line.
Conclusion
Today yous learned how to read a text file into your Python program.
To recap, reading files follows these 3 steps:
- Use theopen() function with the'r' manner to open up a text file.
- Use one of these iii methods:read(),readline(), orreadlines() to read the file.
- Close the file after reading it using theclose() method or let Python do it automatically by using thewith statement.
Conventionally, you can also use the with argument to reading a file. This automatically closes the file for you lot so you do not need to worry most the 3rd pace.
Thank you for reading. Happy coding!
Further Reading
Python—How to Write to a File
10 Useful Python Snippets to Code Like a Pro
Write Python Program to Read Values From Text File
Source: https://www.codingem.com/read-textfile-into-python-program/