How to Read Txt Files in Python

To read a text file in Python:

  1. Open the file.
  2. Read the lines from the file.
  3. Shut the file.

For instance, permit'south read a text file called example.txt from the same folder of the lawmaking file:

with open('instance.txt') every bit file:     lines = file.readlines()

At present the lines variable stores all the lines from example.txt as a listing of strings.

This is the quick answer. 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 process:

  1. Open the file with the built-in open up() part by specifying the path of the file into the call.
  2. Read the text from the file using one of these methods: read(), readline(), readlines().
  3. Close the file using the close() method. You lot tin let Python handle closing the file automatically by opening the file using the with argument.

1. How to Use the open() Function in Python

The basic syntax for calling the open() function is:

open(path_to_a_file, way)

Where:

  • path_to_a_file is the path to the file you desire to open. For example Desktop/Python/instance.txt. If your python programme file is in the same folder as the text file, the path is but the name of the file.
  • fashion specifies in which country y'all want to open the file. In that location are multiple options. But as you lot're interested in reading a file, you only need the mode 'r'.

The open() function returns an iterable file object with which yous can hands read the contents of the file.

For instance, if you accept a file called example.txt in the same folder as your lawmaking file, you can open information technology past:

file = open("instance.txt", "r")

At present the file is opened, but non used in any useful manner yet.

Next, allow's take a look at how to actually read the opened file in Python.

ii. File Reading Methods in Python

To read an opened file, let'due south focus on the three unlike text reading methods: read(), readline(), and readlines():

  • read() reads all the text from a file into a single cord and returns the string.
  • readline() reads the file line past line and returns each line as a split cord.
  • readlines() reads the file line by line and returns the whole file every bit a list of strings, where each string is a line from the file.

Later y'all are going to run across examples of each of these methods.

For instance, permit's read the contents of a file chosen "example.txt" to a variable equally a string:

file = open up("example.txt") contents = file.read()

Now the contents variable has whatsoever is within the file as a single long string.

3. Ever Close the File in Python

In Python, an opened file remains open as long as you lot don't close information technology. And so make sure to shut the file later on using information technology. This tin be washed with the close() method. This is important because the program can crash or the file tin decadent if left hanging open.

file.shut()

You tin also let Python take care of closing the file by using the with statement when dealing with files. In this example, you don't demand the close() method at all.

The with argument structure looks similar this:

with open(path_to_file) as file:     #read the file here

Using the with argument is and so convenient and conventional, that nosotros are going to stick with information technology for the rest of the guide.

At present yous understand the basics of reading files in Python. Side by side, let's take a wait at reading files in action using the different reading functions.

Using the File Reading Methods in Python

To repeat the following examples, create a folder that has the post-obit two files:

  • A reader.py file for reading text files.
  • An example.txt file from where your programme reads the text.

As well, write some text on multiple lines into the example.txt file.

The read() method in Python

To read a file to a single string, utilize the read() method. Every bit discussed above, this reads any is in the file as a single long string into your programme.

For instance, allow'due south read and print out the contents of the case.txt file:

with open("example.txt") as file:     contents = file.read()     print(contents)

Running this slice of lawmaking displays the contents of example.txt in the console:

Hi This is simply an example I demonstrate reading lines

The readline() Method in Python

To read a file one line at a fourth dimension, use the readline() method. This reads the current line in the opened file and moves the line arrow to the next line. To read the whole file, utilise a while loop to read each line and move the file pointer until the finish of the file is reached.

For case:

with open('case.txt') as file:      next_line = file.readline()      while next_line:          impress(next_line)          next_line = file.readline()

Every bit a consequence, this plan prints out the lines one by 1 as the while loop gain:

How-do-you-do  This is just 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, utilize the readlines() method.

When you take read the lines, you tin loop through the list 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 += 1         print(f"line {line_num}: {line}")        

This displays each line in the panel:

line 1: Howdy  line 2: This is only an instance  line 3: I'one thousand demonstrate reading lines

Employ a For Loop to Read an Opened File

You just learned about three different methods you can use to read a file into your Python program.

Information technology is good to realize that the open up() function returns an iterable object. This ways that you lot tin can loop through an opened file just like you would loop through a list in Python.

For example:

with open('example.txt') as file:      for line in file:          impress(line)

Output:

Hi  This is simply an case  I'k demonstrate reading lines

Equally you tin can see, y'all did not need to use whatsoever of the congenital-in file reading methods. Instead, you used a for loop to run through the file line by line.

Conclusion

Today y'all learned how to read a text file into your Python program.

To recap, reading files follows these iii steps:

  1. Use theopen() office with the'r' mode to open a text file.
  2. Use ane of these 3 methods:read(),readline(), orreadlines() to read the file.
  3. Close the file afterwards reading it using theclose() method or let Python do information technology automatically by using thewith statement.

Conventionally, you lot tin can as well use the with statement to reading a file. This automatically closes the file for yous so you practice not demand to worry about the 3rd stride.

Thanks for reading. Happy coding!

Further Reading

Python—How to Write to a File

10 Useful Python Snippets to Lawmaking Like a Pro

thompsonjudis1994.blogspot.com

Source: https://www.codingem.com/read-textfile-into-python-program/

0 Response to "How to Read Txt Files in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel