×

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

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 minutes read.

How to Convert String to List In Python?

How to Convert String to List In Python? We all are familiar with what strings and lists are, let us have a quick revision on them- Strings are a sequence of characters...

4 minutes read.

Why learn Python?

All things considered, learning python would be extraordinary, it'll acquaint you with the universe of dynamic programming dialects, if you're somebody who has had a semester of involvement with C. Python...

4 minutes read.

Python range() function

Python range() function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Syntax range(stop)        or range(start, stop[, step]) Parameter start: It is...

1 minute read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

Slicing of a String in Python

In this tutorial, we will learn about slicing of a string in Python. First of all, let us know what String and Slicing is. String String is a group of characters that...

6 minutes read.

Recursive Multiplication Python

Recursive Multiplication Python In this tutorial, we will learn how to write a Python program to get the multiplication of two numbers using the recursive approach. In the recursive multiplication approach, we...

2 minutes read.

Installing Packages in Python

It's critical to understand that the term "package" here refers to a collection of software that must be installed (i.e. as a synonym for a distribution). It has nothing to...

6 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

Python format() function

Python format() function The format() function in Python formats a specified value into the given format. A ‘TypeErrorexception’ is raised if the method search reaches the object and the format_spec is non-empty, or if either the format_spec or the...

1 minute read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

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.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Python Deep Copy and Shallow Copy

Assignment statements in Python create bindings between a target and an object, not copies of them. The = operator only makes a new variable that shares the reference to the...

3 minutes read.

How to Install PIP In Python

How to Install PIP In Python The libraries for Python have made our work easier than we expected. From a simple addition of two numbers to applying algorithms on the big...

4 minutes read.

Python Word Tokenizer

Python Overview Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. Python is an interpreted language...

4 minutes read.

Python Set difference_update() method

Python Set difference_update() method The set.difference_update() method in Python removes the items that exist in both sets. Syntax set.difference_update(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return None Example 1 # Python program explaining # the set.difference_update()...

2 minutes read.