Read Every Text File in the Folder

Summary: in this tutorial, yous acquire 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: JavaScript ( javascript )

Steps for reading a text file in Python

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

  • Commencement, open a text file for reading by using the open up() part.
  • Second, read text from the text file using the file read(), readline(), or readlines() method of the file object.
  • 3rd, close the file using the file shut() method.

1) open up() function

The open() part has many parameters but you'll be focusing on the first two.

            

open(path_to_file, mode)

The path_to_file parameter specifies the path to the text file.

If the file is in the same folder equally the program, y'all simply demand 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 utilise 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 lot demand to specify the path to the file as c:/sample/readme.txt

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

The following tabular array shows available modes for opening a text file:

Manner Clarification
'r' Open for text file for reading text
'westward' 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 program, you utilise the following code:

            

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

Code language: JavaScript ( javascript )

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

ii) Reading text methods

The file object provides y'all with three methods for reading text from a text file:

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

three) shut() method

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

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

The post-obit 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, yous use the with argument like this:

            

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

Code linguistic communication: JavaScript ( javascript )

In do, you'll use the with statement to close the file automatically.

Reading a text file examples

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

The following example illustrates how to employ 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 language: JavaScript ( javascript )

Output:

            

Beautiful is improve than ugly. Explicit is ameliorate than implicit. Simple is improve than complex. ...

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

            

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

Code language: JavaScript ( javascript )

Output:

            

line 1: Beautiful is ameliorate than ugly. line 2: Explicit is amend than implicit. line 3: Elementary is improve than complex. ...

The following instance shows how to employ 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() impress(line)

Code language: JavaScript ( javascript )

Output:

            

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

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

The open up() 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 equally follows:

            

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

Lawmaking language: JavaScript ( javascript )

This is more concise fashion 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 every bit Japanese, Chinese, and Korean, the text file is not a simple ASCII text file. And information technology's likely a UTF-8 file that uses more than just the standard ASCII text characters.

To open a UTF-eight text file, you lot demand to pass the encoding='utf-8' to the open up() office to instruct it to await UTF-viii characters from the file.

For the sit-in, 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: JavaScript ( javascript )

Output:

Python read utf-8 text file

Summary

  • Utilise the open() office with the 'r' mode to open a text file for reading.
  • Employ the read(), readline(), or readlines() method to read a text file.
  • Always shut a file afterwards completing reading information technology using the shut() method or the with statement.
  • Utilise the encoding='utf-8' to read the UTF-viii text file.

Did you lot find this tutorial helpful ?

galindojoyinewerhat1966.blogspot.com

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

0 Response to "Read Every Text File in the Folder"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel