How to Read Every Text File in a Directory Python

Table of Contents Hide
  1. Steps to Read Text File in Python
    1. Python open() office
    2. Methods for Reading file contents
    3. Python close() function
  2. Examples for Reading a Text file in Python
    1. Example ane – Read the entire text file using the read() part
    2. Example 2 – Read the specific length of characters in a text file using the read() function
    3. Instance 3 – Read a single line in a file using the readline() function
    4. Instance iv- Read text file line by line using the readline() function
    5. Example v – Read all the lines as a list in a file using the readlines() function

Python provides built-in functions to perform file operations, such as creating, reading, and writing files. At that place are mainly ii types of files that Python tin handle, normal text files and binary files. In this tutorial, we volition accept a expect at how to read text files in Python.

Steps to Read Text File in Python

In Python, to read a text file, you demand to follow the below steps.

Stride i: The file needs to be opened for reading using the open() method and laissez passer a file path to the function.

Stride 2: The side by side step is to read the file, and this tin can exist accomplished using several built-in methods such every bit read() , readline() , readlines() .

Step 3: In one case the read operation is performed, the text file must be airtight using the close() office.

At present that nosotros have seen the steps to read the file content allow'south understand each of these methods earlier getting into examples.

Python open() function

The open() function opens the file if possible and returns the corresponding file object.

Syntax – open up(file, fashion='r', buffering=-one, encoding=None, errors=None, newline=None, closefd=True, opener=None)

The open() office has a lot of parameters. Let's have a await at the necessary params for reading the text file. It opens the file in a specified fashion and returns a file object.

Parameters

  • file – path like object which represents the file path
  • style (Optional) – The fashion is an optional parameter. It's a string that specifies the mode in which yous desire to open the file.
Mode Description
'r' Open a file for read mode (default if fashion is non specified)
'w' Open a file for writing. Python will create a new file if does not exist or truncates a file content if file exists
'x' Open a file for exclusive creation.
'a' Open a file for appending the text. Creates a new file if file does not exist.
't' Open up a file in text mode. (default)
'b' Open a file in binary mode.
'+' Open up a file for updating (reading and writing)

Example

              file = open('C:\hello.txt','r')            

Methods for Reading file contents

At that place are three ways to read data from a text file.

  1. read() : The read() office returns the read bytes in the form of string. This method is useful when you have a small file, and yous desire to read the specified bytes or entire file and store it into a string variable.
  2. readline() : The readline() function returns one line from a text file and retuns in the class of cord.
  3. readlines() : The readlines() function reads all the lines from the text file and returns each line as a string element in a list.

Python close() function

The file will remain open up until you shut the file using the close() role. It is a must and all-time practise to perform this operation later on reading the data from the file as it frees upward the retentivity infinite acquired by that file. Otherwise, information technology may cause an unhandled exception.

Examples for Reading a Text file in Python

Case 1 – Read the entire text file using the read() function

In the beneath example, we are reading the entire text file using the read() method. The file can be opened in the read style or in a text mode to read the data, and it can be stored in the string variable.

              # Program to read the unabridged file using read() office file = open("python.txt", "r") content = file.read() print(content) file.shut()   # Program to read the entire file (absolute path) using read() function file = open("C:/Projects/Tryouts/python.txt", "r") content = file.read() print(content) file.shut()            

Output

              Dear User,  Welcome to Python Tutorial  Accept a not bad learning !!!  Thank you            

Example ii – Read the specific length of characters in a text file using the read() function

At that place are times where you need to read the specific bytes in a file. In that example, you lot can apply the read() function by specifying the bytes. The method will output just the specified bytes of characters in a file, as shown beneath.

              # Program to read the specific length  # of characters in a file using read() office file = open("python.txt", "r") content = file.read(twenty) impress(content) file.close()                          

Output

              Dear User,  Welcome            

Example three – Read a single line in a file using the readline() function

If you desire to read a single line in a file, then yous could reach this using readline() function. You lot as well utilize this method to retrieve specific bytes of characters in a line, similar to the read() method.

              # Program to read single line in a file using readline() function file = open up("python.txt", "r") content = file.readline() print(content) file.close()            

Output

              Dear User,                          

Example iv- Read text file line by line using the readline() function

If you want to traverse the file line by line and output in any format, then you lot could use the while loop with the readline() method as shown below. This is the most effective way to read the text file line by line in Python.

              # Plan to read all the lines in a file using readline() function file = open("python.txt", "r") while Truthful: 	content=file.readline() 	if non content: 		pause 	print(content) file.close()                          

Output

              Dearest User,  Welcome to Python Tutorial  Have a swell learning !!!  Cheers            

Case 5 – Read all the lines as a listing in a file using the readlines() function

The readlines() method will read all the lines in the file and outputs in a list of strings, as shown below. Later y'all can use the listing to traverse and extract the specified content from the list.

              # Programme to read all the lines as a list in a file #  using readlines() function  file = open up("python.txt", "r") content=file.readlines() print(content) file.close()                          

Output

              ['Beloved User,\northward', 'Welcome to Python Tutorial\n', 'Have a great learning !!!\n', 'Cheers']            

Ezoic

Sign Up for Our Newsletters

Go notified of the best deals on our WordPress themes.

weilandramplas.blogspot.com

Source: https://itsmycode.com/python-read-text-file/

0 Response to "How to Read Every Text File in a Directory Python"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel