×

Python Parse Text File

We will learn different ways of read text records in Python.

TL;DR

The accompanying tells the best way to read all texts from the readme.txt document into a string:

with open('readme.txt') as f:

lines = f.readlines()

Steps For reading a Text Document in Python

  • To read a text document in Python, you follow these means:
  • In the first place, open a text record for reading by utilizing the open() capability.
  • Second, read text from the text document utilizing the record read(), readline(), or readlines() technique for the record object.
  • Third, close the record utilizing the document close() technique.
  1. open() function:

The open() function has numerous boundaries however you'll zero in on the initial two:

open(path_to_file, mode)

The path_to_file boundary indicates the way to the text record.

Assuming that the program and record are in a similar envelope, you really want to determine just the filename of the document.

In any case, you really want to incorporate the way to the document as well as the filename.

To determine the way to the record, you utilize the forward-slice ('/') regardless of whether you're dealing with Windows.

For instance, if the document readme.txt is put away in the example envelope as the program, you want to determine the way to the record as c:/example/readme.txt

The mode is a discretionary boundary. A string determines the mode wherein you need to open the document.

 The accompanying table shows accessible modes for opening a text record:

Mode and Description

  • 'r’ means Open for text record for understanding text
  • 'w' means Open a text record for composing text
  • 'a' means Open a text record for affixing text

For instance, to open a document whose name is the-harmony of-python.txt put away in a similar envelope as the program, you utilize the accompanying code:

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

The open() capability returns a record object which you will use to peruse text from a text document.

2. reading  text strategies

The document object furnishes you with three strategies for reading text from a text record:

  • read(size) - read a few items in a record in view of the discretionary size and return the items as a string. On the off chance that you overlook the size, the read() technique peruses from where it left off till the finish of the document. In the event that the finish of a document has been reached, the read() strategy returns an unfilled string.
  • readline() - read a solitary line from a text record and return the line as a string. On the off chance that the finish of a record has been reached, the readline() returns an unfilled string.
  • readlines() - read every one of the lines of the text record into a rundown of strings. This strategy is helpful to control the entire text of that record.

3. close() technique

The record that you open will stay open until you close it utilizing the nearby() strategy.

It's vital to close the record that is presently not being used for the accompanying reasons:

In the first place, when you open a document in your content, the record framework typically secures it so no different projects or scripts can utilize it until you close it.

Second, your record framework has a predetermined number of document descriptors that you can make before it runs out of them.

Although this number may be high, it's feasible to open a ton of documents and exhaust your record framework assets.

Third, leaving many records open might prompt race conditions which happen when various cycles endeavor to alter one document simultaneously and can cause a wide range of startling ways of behaving.

The accompanying tells the best way to call the nearby() technique to close the record:

f.close()

To close the document consequently without calling the nearby() technique, you utilize the with explanation like this:

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

By and by, you'll utilize with articulation to naturally close the document.

Reading a text document models:

  • We'll utilize the-harmony of-python.txt document for the exhibition.
  • The accompanying model outlines how to utilize the read() strategy to peruse every one of the items in the-harmony of-python.txt document into a string:
withopen('the-harmony of-python.txt') as f:
    contents = f.read()
    print(contents)

Output:

Wonderful is better compared to revolting.
Express is better compared to certain.
Basic is superior to complex.
  • The accompanying model purposes the readlines() strategy to peruse the text record and returns the document contents as a rundown of strings:
with open('the-harmony of-python.txt') as f:
    [print(line) for line in f.readlines()]

Output:

Delightful is better compared to appalling.
Express is better compared to implied.
Straightforward is superior to complex.
Complex is better compared to convoluted.
  • The explanation you see a clear line after each line from a record is that each line in the text document has a newline character (\n).
  • To eliminate the clear line, you can utilize the strip() technique. For instance:
with open('the-harmony of-python.txt') as f:
    [print(line.strip()) for line in f.readlines()]
  • The accompanying model tells the best way to utilize the readline() to peruse the text record line by line:
with open('the-harmony of-python.txt') as f:
    while Valid:
        line = f.readline()
        on the off chance that not line:
            break
        print(line.strip())

Output:

Unequivocal is better compared to verifiable.
Complex is better compared to muddled.
Level is better compared to settled.

A more brief method for perusing a text document line by line:

  • The open() capability returns a record object which is an iterable item. Subsequently, you can utilize a for circle to emphasize over the lines of a text document as follows:
with open('the-harmony of-python.txt') as f:
    for line in f:
  • This is a more succinct method for perusing a text record line by line.

Peruse UTF-8 Text Records:

  • The code in the past models turns out great with ASCII text records. In any case, in the event that you're managing different dialects like Japanese, Chinese, and Korean, the text record is definitely not a basic ASCII text document. Furthermore, it's probable an UTF-8 document that utilizes something beyond the standard ASCII text characters.
  • To open an UTF-8 text record, you really want to pass the encoding='utf-8' to the open() capability to train it to anticipate UTF-8 characters from the document.
  • For the show, you'll utilize the accompanying quotes.txt record that contains a few statements in Japanese.
  • The accompanying tells the best way to circle through the quotes.txt record:
with open('quotes.txt', encoding='utf8') as f:
    for line in f:
        print(line.strip())

Conclusion:

  • Utilize the open() capability with the 'r' mode to open a text document for perusing.
  • Utilize the read(), readline(), or readlines() strategy to peruse a text document.
  • Continuously close a document in the wake of finishing perusing it utilizing the nearby() technique or the with explanation.
  • Utilize the encoding='utf-8' to peruse the UTF-8 text document

Related Topics

Python Program for Linear Search

Introduction We employ specific algorithms to efficiently carry out our responsibilities, such as searching for an element in a given data structure. These algorithms fall under the category of searching algorithms....

4 minutes read.

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

Python | Read csv using pandas.read_csv()

Python is an excellent language for performing information analysis, owing to the fantastic biological system of information-driven python packages. Pandas is one of those packages that make taking in and...

4 minutes read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

How to create a login page in python

Users can access an application by providing their username and Password or by authenticating with a social media login on the login screen. Python Tkinter Python provides a variety of choices for...

3 minutes read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

Python SQLite

SQLite It is an RDBMS (Relational Database Management System). It is an embedded, serverless, transactional SQL database engine. It is an open-source application. It is named SQLite because of its lightweight....

3 minutes read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

How to convert integer to float in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

5 minutes read.

Classes & Objects in Python

Classes and Objects are used in most modern programming languages, mainly in Object-oriented Programming languages. What is meant by Object Oriented Programming language? Usage of objects and their components in order to...

7 minutes read.

Python reversed() Function

Python reversed() Function The reversed() in Python returns a reverse iterator. Syntax reversed(seq) Parameter seq: This parameter represents any iterable object. Return This function returns a reversed iterator object. Example 1 # Python Program describing # the reversed() function ...

1 minute read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

GET and POST requests using Python

‘GET’ and ‘POST’ are two request methods of Hypertext Transfer Protocol (HTTP). What is HTTP? HTTP stands for Hypertext Transfer Protocol. It is a collection of protocols which makes communication between client...

4 minutes read.

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

Python pow() Function

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Operator Overloading in Python

In any programming language, + is an arithmetic operator; it adds two numbers to give the sum. Have you ever tried to concatenate two strings? Concatenating two strings is adding...

5 minutes read.