Read a String/ Paragraph, (a Method in Your Class to Read From the User)

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

TL;DR

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

            

with open('readme.txt') equally f: lines = f.readlines()

Code language: JavaScript ( javascript )

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 up() 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 shut() method.

i) open() function

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

            

open(path_to_file, fashion)

The path_to_file parameter specifies the path to the text file.

If the file is in the same folder as the program, you merely demand to specify the name of the file. Otherwise, you demand to specify the path to the file.

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

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

The fashion is an optional parameter. It's a cord that specifies the mode in which yous want to open the file.

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

Mode Clarification
'r' Open for text file for reading text
'w' Open up 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 programme, you use the following code:

            

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

Code linguistic communication: JavaScript ( javascript )

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

2) Reading text methods

The file object provides y'all 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 take a minor 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 equally strings.
  • readlines() – read all the lines of the text file and return them every bit a list of strings.

3) close() method

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

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

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

            

f .shut()

Code linguistic communication: CSS ( css )

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

            

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

Code language: JavaScript ( javascript )

In do, you lot'll utilise the with argument to shut 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: JavaScript ( javascript )

Output:

            

Cute is improve than ugly. Explicit is meliorate than implicit. Simple is ameliorate than complex. ...

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

            

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

Code language: JavaScript ( javascript )

Output:

            

line 1: Beautiful is better than ugly. line ii: Explicit is better than implicit. line 3: Simple is better than circuitous. ...

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)

Code language: JavaScript ( javascript )

Output:

            

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

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

The open up() function returns a file object which is an iterable object. Therefore, you can apply a for loop to iterate over the lines of a text file every bit 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-viii 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 elementary ASCII text file. And it'due south likely a UTF-eight file that uses more than than simply the standard ASCII text characters.

To open a UTF-8 text file, you need to pass the encoding='utf-8' to the open up() function to instruct information technology to expect UTF-8 characters from the file.

For the demonstration, you'll utilise 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') as f: for line in f: impress(line.strip())

Code language: JavaScript ( javascript )

Output:

Python read utf-8 text file

Summary

  • Use the open() role with the 'r' manner to open up a text file for reading.
  • Use the read(), readline(), or readlines() method to read a text file.
  • Ever close a file after completing reading it using the shut() method or the with statement.
  • Use the encoding='utf-eight' to read the UTF-8 text file.

Did yous find this tutorial helpful ?

boycepenot1954.blogspot.com

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

0 Response to "Read a String/ Paragraph, (a Method in Your Class to Read From the User)"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel