Read and Print Fine Line by Line Python

Summary: in this tutorial, you lot 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') every bit f: lines = f.readlines()

Code language: JavaScript ( javascript )

Steps for reading a text file in Python

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

  • First, open a text file for reading by using the open up() part.
  • 2nd, 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.

one) open() role

The open up() function has many parameters but you'll exist focusing on the first two.

            

open(path_to_file, way)

The path_to_file parameter specifies the path to the text file.

If the file is in the same folder as the program, you lot simply need to specify the name of the file. Otherwise, you need to specify the path to the file.

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

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

The mode is an optional parameter. It's a string that specifies the way in which you want to open the file.

The following table shows available modes for opening a text file:

Style Clarification
'r' Open for text file for reading text
'w' Open a text file for writing text
'a' Open up a text file for appending text

For example, to open up a file whose proper name is the-zen-of-python.txt stored in the same folder equally the program, y'all use the following lawmaking:

            

f = open('the-zen-of-python.txt','r')

Code language: JavaScript ( javascript )

The open() part returns a file object which yous will apply to read text from a text file.

ii) Reading text methods

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

  • read() – read all text from a file into a string. This method is useful if you have a small file and you lot want to manipulate the whole text of that file.
  • readline() – read the text file line by line and return all the lines as strings.
  • readlines() – read all the lines of the text file and return them as a list of strings.

3) close() method

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

Information technology's important to close the file that is no longer in employ. If you don't close the file, the plan may crash or the file would be corrupted.

The post-obit shows how to telephone call the close() method to close the file:

            

f .close()

Code linguistic communication: CSS ( css )

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

            

with open(path_to_file) as f: contents = f.readlines()

Lawmaking language: JavaScript ( javascript )

In practice, you'll employ the with statement to shut the file automatically.

Reading a text file examples

Nosotros'll utilise the-zen-of-python.txt file for the sit-in.

The post-obit 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') every bit f: contents = f.read() print(contents)

Code linguistic communication: JavaScript ( javascript )

Output:

            

Beautiful is better than ugly. Explicit is better than implicit. Simple is better than circuitous. ...

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

            

lines = [] with open('the-zen-of-python.txt') as f: lines = f.readlines() count = 0 for line in lines: count += one print(f'line {count}: {line}')

Code language: JavaScript ( javascript )

Output:

            

line 1: Beautiful is better than ugly. line 2: Explicit is better than implicit. line iii: Uncomplicated is better than complex. ...

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

            

with open up('the-zen-of-python.txt') as f: line = f.readline() while line: line = f.readline() impress(line)

Lawmaking language: JavaScript ( javascript )

Output:

            

Explicit is better than implicit. Simple is better than circuitous. Complex is amend than complicated. ...

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

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

            

with open up('the-zen-of-python.txt') as f: for line in f: print(line)

Lawmaking language: JavaScript ( javascript )

This is 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 y'all're dealing with other languages such as Japanese, Chinese, and Korean, the text file is not a unproblematic ASCII text file. And it's likely a UTF-8 file that uses more merely the standard ASCII text characters.

To open a UTF-8 text file, you need to laissez passer the encoding='utf-8' to the open() role to instruct it to expect UTF-eight characters from the file.

For the sit-in, yous'll use the post-obit 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') equally f: for line in f: print(line.strip())

Code language: JavaScript ( javascript )

Output:

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 information technology using the close() method or the with argument.
  • Use the encoding='utf-8' to read the UTF-8 text file.

Did you observe this tutorial helpful ?

johnsondecten.blogspot.com

Source: https://www.pythontutorial.net/python-basics/python-read-text-file/

0 Response to "Read and Print Fine Line by Line Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel