Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract text, line by line from a txt file in python

I have a txt file like this :

audi lamborghini
ferrari
pagani

when I use this code :

with open("test.txt") as inp:
    data = set(inp.read().split())

this gives data as : ['pagani', 'lamborghini', 'ferrari', 'audi']

What I want, is to extract text from the txt file, line by line such the output data is

['audi lamborghini','ferrari','pagani']

How this can be done ?

like image 462
Vipul Avatar asked Jan 22 '26 22:01

Vipul


2 Answers

data = inp.read().splitlines()

You could do

data = inp.readlines()

or

data = list(inp)

but the latter two will leave newline characters on each line, which tends to be undesirable.

Note that since you care about order, putting your strings into any sort of set is not advisable - that destroys order.

like image 104
roippi Avatar answered Jan 25 '26 13:01

roippi


Because file objects are iterable, you can just do:

with open("test.txt") as inp:
    data = list(inp) # or set(inp) if you really need a set

(documentation reference)

Alternatively, more verbose (with list comprehension you can remove trailing newlines here also):

with open("test.txt") as inp:
    data = inp.readlines()

or (not very Pythonic, but gives you even more control):

data = []
with open("test.txt") as inp:
    for line in inp:
        data.append(line)
like image 35
BartoszKP Avatar answered Jan 25 '26 13:01

BartoszKP