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 ?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With