Skip to content Skip to sidebar Skip to footer

Python Read a File in as String

Summary: in this tutorial, yous learn diverse 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()

Lawmaking linguistic communication: JavaScript ( javascript )

Steps for reading a text file in Python

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

  • Kickoff, open a text file for reading by using the open() 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.

1) open up() function

The open() office has many parameters merely you'll be focusing on the kickoff 2.

            

open(path_to_file, fashion)

The path_to_file parameter specifies the path to the text file.

If the file is in the aforementioned binder equally the program, yous just 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 y'all're working in Windows.

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

The mode is an optional parameter. It'due south 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:

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

For case, to open up a file whose name is the-zen-of-python.txt stored in the aforementioned folder as the program, you apply the following code:

            

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

Code language: JavaScript ( javascript )

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

two) Reading text methods

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

  • read() – read all text from a file into a cord. This method is useful if you accept a pocket-size file and you 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) shut() method

The file that you open up will remain open until you close information technology using the shut() method.

It'southward important to close the file that is no longer in employ. If you lot don't close the file, the plan may crash or the file would exist corrupted.

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

            

f .close()

Code language: CSS ( css )

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

            

with open(path_to_file) every bit f: contents = f.readlines()

Code language: JavaScript ( javascript )

In practice, y'all'll use the with statement to shut the file automatically.

Reading a text file examples

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

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 cord:

            

with open('the-zen-of-python.txt') as f: contents = f.read() print(contents)

Code linguistic communication: JavaScript ( javascript )

Output:

            

Beautiful is better than ugly. Explicit is better than implicit. Simple is amend than complex. ...

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

            

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

Lawmaking language: JavaScript ( javascript )

Output:

            

line 1: Cute is better than ugly. line 2: Explicit is amend than implicit. line three: Simple is better than complex. ...

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

            

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

Code language: JavaScript ( javascript )

Output:

            

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

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 tin 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)

Lawmaking language: JavaScript ( javascript )

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

Read UTF-8 text files

The code in the previous examples works fine with ASCII text files. Notwithstanding, if y'all're dealing with other languages such every bit Japanese, Chinese, and Korean, the text file is not a simple ASCII text file. And it's likely a UTF-eight file that uses more than than only the standard ASCII text characters.

To open a UTF-8 text file, you need to pass the encoding='utf-8' to the open() part to instruct it to wait UTF-8 characters from the file.

For the demonstration, you'll employ 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())

Lawmaking language: JavaScript ( javascript )

Output:

Python read utf-8 text file

Summary

  • Utilize the open() office with the 'r' mode to open a text file for reading.
  • Utilize 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 argument.
  • Use the encoding='utf-8' to read the UTF-8 text file.

Did you notice this tutorial helpful ?

trotternatchoughe.blogspot.com

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

Post a Comment for "Python Read a File in as String"