Reputation: 4168
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 ?
Upvotes: 3
Views: 16901
Reputation: 35891
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
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)
Upvotes: 4
Reputation: 629
You can try the readlines command which would return a list.
with open("test.txt") as inp: data = set(inp.readlines())
In case of the doing.
data = set(inp.read().split())
You are first reading the whole file as one string (inp.read()), then you are using split() on that which causes the string to be split on whitespaces.
Upvotes: 2
Reputation: 25954
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.
Upvotes: 7