×

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

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.

Python Set remove() method

Python Set remove() method The set.remove() method in Python removes the specified element from the set if it is present in the set else this method will raise an error if the specified item does...

2 minutes read.

One Liner If-Else Statements in Python

Before learning one liner if else Python, let us first know what Python is. Python is a broadly helpful, object-oriented and dependable language having a large number of utilizations from...

4 minutes read.

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.

List Index out of Range Python for Loop

The List is generally used in Python to store multiple items or elements inside one single variable. The List is ordered in nature, the List can contain the elements inside...

3 minutes read.

How to build a Virtual Assistant Using Python

What is a virtual assistant? A virtual assistant is a new and very interesting concept in today’s world. When we hear the word “Virtual Assistant”, we can easily visualize “Jarvis or...

8 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

Genetic Algorithm in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The source...

4 minutes read.

Polymorphism in Python

What is polymorphism and why is it important? Polymorphism's literal definition is the state of occurring in diverse shapes or forms. When it comes to programming, the idea of polymorphism is crucial....

3 minutes read.

Python Dictionary popitem() method

Python Dictionary popitem() method The dictionary.popitem() method in Python removes the item that was last inserted into the dictionary. Syntax dictionary.popitem() Parameter NA Return This method returns an arbitrary element (key, value) pair from the given dictionary...

1 minute read.

How to check if the dictionary is empty in Python?

What is a dictionary in Python? A directory is a collection of data but data is not ordered. Unlike other data types, it does not hold a single value as its...

3 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

Python K-Means Clustering

K-Means Clustering is a basic yet incredible calculation in information scienceThere are a plenty of true utilizations of K-Means clustering (a couple of which we will cover here)This far reaching...

25 minutes read.

Python Dictionary values() method

Python Dictionary values() method The dictionary.values() method in Python returns a view object that displays a list of all the values in the specified dictionary. Syntax dictionary.values() Parameter NA Return This method returns a view object. The...

1 minute read.

Python Built-in Functions

Python Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. The Python built- in functions are as follow: Methods Explaining abs() The abs() function returns...

6 minutes read.

Inheritance in Python

Inheritance in Python Object-Oriented Programming provides reusable patterns to the code for restricting the redundancy in development projects. One of the basic principles of Object-Oriented Programming that helps achieve recyclable code...

8 minutes read.

Python String join() method

Python String join() method The String.join() method in Python concatenates each element of an iterable (such as list, string and tuple) to the given string and returns the concatenated string. Syntax string.join(seq) Parameter Seq: This...

1 minute read.