Read a Text File and Rename a File

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

In Python, at that place are a few ways you tin can read a text file.

In this commodity, I will become over the open() 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, y'all first have to open information technology.

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

                open up("name of file y'all want opened", "optional manner")              

File names and correct paths

If the text file and your current file are in the same directory ("folder"), and then you lot can just reference the file name in the open() function.

                open up("demo.txt")              

Hither is an instance 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 different directory, then you volition need to reference the right path name for the text file.

In this example, the random-text file is inside a unlike folder so chief.py:

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

In club to access that file in the principal.py, you have to include the binder name with the name of the file.

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

If you don't have the right path for the file, and so yous volition get an error bulletin similar this:

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

It is really of import to continue track of which directory you are in so you can reference the correct path name.

Optional Mode parameter in open()

There are different modes when you lot are working with files. The default manner is the read mode.

The letter r stands for read fashion.

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

You tin can also omit mode= and only write "r".

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

In that location are other types of modes such as "w" for writing or "a" for appending.  I am not going to go into particular for the other modes because we are just going to focus on reading files.

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

Additional parameters for the open() office in Python

The open() function tin can accept in these optional parameters.

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

To acquire more most these optional parameters, please read through the documentation.

What is the readable() method in Python?

If you desire to cheque if a file can be read, then you can apply the readable() method. This volition return a Truthful or False.

This example would render True considering we are in the read mode:

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

If I inverse this case, to "w" (write) way, then the readable() method would return Imitation:

                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 ane string. This is a adept method to utilise if you don't accept a lot of content in the text file.

In this example, I am using the read() method to print out a listing 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 can take in an optional parameter called size. Instead of reading the whole file, but a portion of information technology will be read.

If we modify the earlier case, we can print out only the first discussion by calculation the number 4 every bit an statement for read().

                file = open("demo.txt") print(file.read(4))              
Screen-Shot-2021-09-13-at-3.01.30-AM

If the size argument is omitted, or if the number is negative, then the whole file will exist read.

What is the shut() method in Python?

Once you are done reading a file, it is important that you shut it. If you forget to shut your file, and so 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 utilise the with keyword to close files in Python

One way to ensure that your file is airtight is to use the with keyword. This is considered good practice, considering the file volition close automatically instead of you having to manually shut information technology.

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

In this example, nosotros have a text file with these two sentences:

                This is the outset line This is the second line              

If nosotros use the readline() method, it will just print the first sentence of the file.

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

This method besides takes in the optional size parameter. We can change the example to add the number 7 to only read and print out This is:

                with open("demo.txt") as 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, we are going to print out our grocery items as a list using the readlines() method.

                with open("demo.txt") as file:     print(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 culling to these different read methods would be 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 item in file:         print(item)              
Screen-Shot-2021-09-13-at-4.27.49-AM

Conclusion

If you lot want to read a text file in Python, yous get-go have to open it.

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

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

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

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

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

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

                file.readable()              

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

                file.read()              

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

                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 render that.

                file.readline()              

The readlines() method will read and return a listing of all of the lines in the file.

                file.readlines()              

An alternative to these dissimilar read methods would be to use a for loop.

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

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



Larn to code for free. freeCodeCamp's open source curriculum has helped more 40,000 people get jobs as developers. Get started

joneshaped1939.blogspot.com

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

0 Response to "Read a Text File and Rename a File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel