Read Txt File That Is Not in the Same Directory

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

In Python, at that place are a few ways you tin 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 up() function in Python?

If you lot desire to read a text file in Python, you commencement take to open it.

This is the bones 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"), and so you lot tin just reference the file name in the open() function.

                open up("demo.txt")              

Hither is an example of both files existence in the same directory:

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

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

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

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

In club to admission that file in the principal.py, yous have to include the folder proper noun with the name of the file.

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

If yous don't accept the correct path for the file, then y'all will get an fault bulletin like this:

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

It is actually of import to go on runway of which directory you are in so you can reference the right path proper name.

Optional Way parameter in open()

There are unlike modes when you are working with files. The default way is the read mode.

The alphabetic character r stands for read mode.

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

You can as well omit way= and just write "r".

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

At that place are other types of modes such as "w" for writing or "a" for appending.  I am non going to go into detail for the other modes because we are just going to focus on reading files.

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

Additional parameters for the open() function in Python

The open() part 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 desire to cheque if a file tin can be read, and so you can apply the readable() method. This volition render a True or Faux.

This case would return True because 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 example, to "west" (write) mode, then the readable() method would return Fake:

                file = open("demo.txt", "due west") 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 1 string. This is a good 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 up("demo.txt") print(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, simply a portion of information technology volition be read.

If we modify the earlier case, we tin can print out only the starting time word by adding the number iv as an argument for read().

                file = open up("demo.txt") print(file.read(iv))              
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 be read.

What is the shut() method in Python?

Once you are washed reading a file, it is important that you close it. If you forget to close your file, then that tin cause problems.

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

                file = open up("demo.txt") print(file.read()) file.shut()              

How to utilize the with keyword to close files in Python

One way to ensure that your file is closed is to utilise the with keyword. This is considered good practice, 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:     impress(file.read())              

What is the readline() method in Python?

This method is going to read ane line from the file and render that.

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

                This is the first line This is the second line              

If nosotros utilise the readline() method, it will just print the start judgement of the file.

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

This method as well takes in the optional size parameter. We tin alter the example to add together the number 7 to only read and impress 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") equally file:     print(file.readlines())              
Screen-Shot-2021-09-13-at-4.19.23-AM

How to apply a for loop to read lines from a file in Python

An alternative to these different read methods would be to apply a for loop.

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

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

Determination

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

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

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() function.

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

The open() role takes in the optional mode parameter. The default manner is the read style.

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

If y'all want to check if a file tin can be read, so you can utilise 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 1 string.

                file.read()              

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

                file.shut()              

One style 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 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") as file:     for item in file:         impress(detail)              

I hope you enjoyed this article and best of luck on your Python journey.



Learn to lawmaking for free. freeCodeCamp'southward open source curriculum has helped more 40,000 people become jobs as developers. Get started

tyrrelldifewore.blogspot.com

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

0 Response to "Read Txt File That Is Not in the Same Directory"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel