Open and read text file in python

Python Read Text File

Summary: in this tutorial, you learn various ways to read text files in Python.

TL;DR

The following shows how to read all texts from the readme.txt file into a string:

with open('readme.txt') as f: lines = f.readlines()Code language: Python (python)

Steps for reading a text file in Python

To read a text file in Python, you follow these steps:

  • First, open a text file for reading by using the open() function.
  • Second, read text from the text file using the file read() , readline() , or readlines() method of the file object.
  • Third, close the file using the file close() method.

1) open() function

The open() function has many parameters but you’ll be focusing on the first two:

open(path_to_file, mode)Code language: Python (python)

The path_to_file parameter specifies the path to the text file.

Читайте также:  Set interface methods in java

If the program and file are in the same folder, you need to specify only the filename of the file. Otherwise, you need to include the path to the file as well as the filename.

To specify the path to the file, you use the forward-slash ( ‘/’ ) even if you’re working on Windows.

For example, if the file readme.txt is stored in the sample folder as the program, you need to specify the path to the file as c:/sample/readme.txt

The mode is an optional parameter. It’s a string that specifies the mode in which you want to open the file. The following table shows available modes for opening a text file:

Mode Description
‘r’ Open for text file for reading text
‘w’ Open a text file for writing text
‘a’ Open a text file for appending text

For example, to open a file whose name is the-zen-of-python.txt stored in the same folder as the program, you use the following code:

 f = open('the-zen-of-python.txt','r')Code language: Python (python)

The open() function returns a file object which you will use to read text from a text file.

2) Reading text methods

The file object provides you with three methods for reading text from a text file:

  • read(size) – read some contents of a file based on the optional size and return the contents as a string. If you omit the size, the read() method reads from where it left off till the end of the file. If the end of a file has been reached, the read() method returns an empty string.
  • readline() – read a single line from a text file and return the line as a string. If the end of a file has been reached, the readline() returns an empty string.
  • readlines() – read all the lines of the text file into a list of strings. This method is useful if you have a small file and you want to manipulate the whole text of that file.

3) close() method

The file that you open will remain open until you close it using the close() method.

It’s important to close the file that is no longer in use for the following reasons:

  • First, when you open a file in your script, the file system usually locks it down so no other programs or scripts can use it until you close it.
  • Second, your file system has a limited number of file descriptors that you can create before it runs out of them. Although this number might be high, it’s possible to open a lot of files and deplete your file system resources.
  • Third, leaving many files open may lead to race conditions which occur when multiple processes attempt to modify one file at the same time and can cause all kinds of unexpected behaviors.

The following shows how to call the close() method to close the file:

f.close()Code language: Python (python)

To close the file automatically without calling the close() method, you use the with statement like this:

with open(path_to_file) as f: contents = f.readlines()Code language: Python (python)

In practice, you’ll use the with statement to close the file automatically.

Reading a text file examples

We’ll use the-zen-of-python.txt file for the demonstration.

The following example illustrates how to use the read() method to read all the contents of the the-zen-of-python.txt file into a string:

with open('the-zen-of-python.txt') as f: contents = f.read() print(contents)Code language: Python (python)
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. . Code language: Python (python)

The following example uses the readlines() method to read the text file and returns the file contents as a list of strings:

with open('the-zen-of-python.txt') as f: [print(line) for line in f.readlines()]Code language: Python (python)
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. . Code language: Python (python)

The reason you see a blank line after each line from a file is that each line in the text file has a newline character (\n). To remove the blank line, you can use the strip() method. For example:

with open('the-zen-of-python.txt') as f: [print(line.strip()) for line in f.readlines()]Code language: Python (python)

The following example shows how to use the readline() to read the text file line by line:

with open('the-zen-of-python.txt') as f: while True: line = f.readline() if not line: break print(line.strip())Code language: Python (python)
Explicit is better than implicit. Complex is better than complicated. Flat is better than nested. . Code language: Python (python)

A more concise way to read a text file line by line

The open() function returns a file object which is an iterable object. Therefore, you can use a for loop to iterate over the lines of a text file as follows:

with open('the-zen-of-python.txt') as f: for line in f: print(line.strip())Code language: Python (python)

This is a more concise way to read a text file line by line.

Read UTF-8 text files

The code in the previous examples works fine with ASCII text files. However, if you’re dealing with other languages such as Japanese, Chinese, and Korean, the text file is not a simple ASCII text file. And it’s likely a UTF-8 file that uses more than just the standard ASCII text characters.

To open a UTF-8 text file, you need to pass the encoding=’utf-8′ to the open() function to instruct it to expect UTF-8 characters from the file.

For the demonstration, you’ll use the following quotes.txt file that contains some quotes in Japanese.

The following shows how to loop through the quotes.txt file:

with open('quotes.txt', encoding='utf8') as f: for line in f: print(line.strip())Code language: Python (python)

Python read utf-8 text file

Summary

  • Use the open() function with the ‘r’ mode to open a text file for reading.
  • Use the read() , readline() , or readlines() method to read a text file.
  • Always close a file after completing reading it using the close() method or the with statement.
  • Use the encoding=’utf-8′ to read the UTF-8 text file.

Источник

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

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

In Python, there are a few ways you 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() function in Python?

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

This is the basic 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»), then you can just reference the file name in the open() function.

Here is an example of both files being 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 will need to reference the correct path name for the text file.

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

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

In order to access that file in the main.py , you have to include the folder name with the name of the file.

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

If you don’t have the correct path for the file, then you will get an error message like this:

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

It is really important to keep 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 are working with files. The default mode is the read mode.

The letter r stands for read mode.

You can also omit mode= and just write «r» .

There are other types of modes such as «w» for writing or «a» for appending. I am not 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() function can take in these optional parameters.

To learn more about these optional parameters, please read through the documentation.

What is the readable() method in Python?

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

This example would return True because we are in the read mode:

file = open("demo.txt") print(file.readable())

If I changed this example, to «w» (write) mode, then the readable() method would return False :

file = open("demo.txt", "w") print(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 string. This is a good method to use if you 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("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, only a portion of it will be read.

If we modify the earlier example, we can print out only the first word by adding the number 4 as an argument for read() .

file = open("demo.txt") print(file.read(4))

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

What is the close() method in Python?

Once you 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") print(file.read()) file.close()

How to use 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 practice, because the file will close automatically instead of you having to manually close it.

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

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

This is the first line This is the second line

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

with open("demo.txt") as file: print(file.readline())

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

This method also takes in the optional size parameter. We can modify 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 alternative to these different read methods would be to use a for loop .

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

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

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

Conclusion

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 need to reference the correct path name for the text file.

The open() function takes in the optional mode parameter. The default mode is the read mode.

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

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

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

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

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

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

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

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

Источник

Оцените статью