Python open file and read all lines

How to Read a File Line by Line in Python

Dionysia Lemonaki

Dionysia Lemonaki

How to Read a File Line by Line in Python

When coding in Python, there may be times when you need to open and read the contents of a text file.

Luckily enough, there are several ways to do this in Python.

The language has many built-in functions, methods, and keywords that you can use to create, write, read and delete text files.

In this article, you’ll learn the most common ways of reading a file. With the help of coding examples, you will know how to read a text file line by line.

Here is what we will cover:

How to Open a Text File Using the open() Function in Python

Before you start reading a text file in Python, you first need to open it.

To open a text file, use the built-in open() function.

The general syntax for the open() function looks like this:

The open() function accepts multiple arguments, but in this example, I’m focusing only on two: filename and mode .

Let’s break down the syntax.

The first required argument that the open() function accepts is filename , which represents the full path of the file name you want to open.

When specifying the path of the file you want to open, you need to be aware of where that file is located in your folder structure.

For example, if the text file you want to open and your current file with Python code are in the same folder, you only need to reference its name and extension.

Say you have a folder with the name projects .

Inside it, you have two files, main.py , which is the file where you write your Python code, and example.txt , which is the file you would like to open. That file contains the following contents:

I absolutely love coding! I am learning to code for free with freeCodeCamp! 

Both files are on the same level in the folder, so here is how you would reference example.txt when using the open() function:

The second optional argument that the open() function accepts is mode . It specifies whether you want to read ( «r» ), write ( «w» ), or append ( «a» ) to filename .

The default mode is the read ( «r» ) mode.

So, to open and read example.txt , you could optionally use «r» to represent the mode you want to use:

With that said, you don’t need to write the keyword mode .

Instead, you can omit it and only use the letter «r» — it would still have the same result:

Lastly, you can omit the letter «r» altogether as it is the default mode:

When you run the code from the example above, it doesn’t do anything.

You completed the first step, which is opening the text file, but you haven’t read it and seen its contents.

Читайте также:  Python edit excel file

How to Read a Text File Using the read() Method in Python

To read the contents of example.txt , let’s first store the code we wrote in the previous section in a variable named file :

Then, let’s call the read() method on file and print the result to the console:

file = open("example.txt") print(file.read()) # output # I absolutely love coding! # I am learning to code for free with freeCodeCamp! 

Now, you can read the contents of example.txt !

The read() method reads all the contents as a single string, which is useful when working with smaller files that don’t have a lot of content in the text file.

With that said, the code above is missing something.

Once you have finished reading the text file, you need to close it. To do that, use the close() method. Make sure not to skip this step because forgetting to close the file may introduce bugs in your code!

file = open("example.txt") print(file.read()) # close file file.close() 

Now, closing the text file is a good practice, but it is something that you can easily forget to do — you may not always remember to call the close() method on the file.

There is an alternative available.

The with keyword ensures that the file is automatically closed upon code execution.

The general syntax for the with keyword when used with the open() function is the following:

with open("filename") as variable: # do something with variable 

So, here is how you would rewrite the code from the previous example using the with keyword instead of the close() method:

with open("example.txt") as file: print(file.read()) # output # I absolutely love coding! # I am learning to code for free with freeCodeCamp! 

How to Read a Text File Using the readline() Method in Python

If you want to read only one single individual line from a text file, use the readline() method:

with open("example.txt") as file: print(file.readline()) # output # I absolutely love coding! 

The text file example.txt has two lines inside it, but the readline() method only reads one line from the file and returns it.

The readline() method also adds a trailing newline character at the end of the string.

You can optionally pass a size argument to the readline() method, which specifies the length of the returned line and the maximum number of bytes it will read.

with open("example.txt") as file: print(file.readline(10)) # output # I absolute 

How to Read a Text File Using the readlines() Method in Python

The readlines() method reads all the lines from a file, going through the file line by line.

It then returns a list of strings:

with open("example.txt") as file: print(file.readlines()) # output # ['I absolutely love coding!\n', 'I am learning to code for free with freeCodeCamp!'] 

The readlines() method read all the lines in one go and stored each line from the text file as a single list item inside a list. The readlines() method also added a newline character \n at the end of each line.

How to Read a Text File Using a for Loop in Python

An alternative way of reading a file line by line in Python is using a for loop, which is the most Pythonic approach to reading a file:

with open("example.txt") as file: for item in file: print(item) # output # I absolutely love coding! # I am learning to code for free with freeCodeCamp! 

The open() function returns an iterable object.

The for loop gets paired with the in keyword — they iterate over the returned iterable file object and read each line inside it.

Conclusion

Hopefully, this article helped you understand how to read a file line by line in Python using the read() , readline() , and readlines() methods and a for loop.

Читайте также:  Python pandas показать все данные

Thank you for reading, and happy coding!

Источник

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.

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.
Читайте также:  Shapiro wilk test python

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.

Источник

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