Reputation: 31
I have a .txt file:
My
name is
Richard
And I want to get something like ['My', 'name is', 'Richard']
.
I tried
file = open("Text.txt")
strings = file.read()
strings = strings.split()
print(strings)
But it gives me ['My', 'name', 'is', 'Richard']
. So how can I get it line by line?
Upvotes: 2
Views: 4499
Reputation: 6915
Just use
strings = strings.splitlines()
instead of
strings = strings.split()
The splitlines
method splits a string by newline characters.
Upvotes: 0
Reputation: 2796
There's an integrated function for this called readlines()
. There is a Tutorials Point article about it, and it's in the Python documentation as well.
You would use it like so.
with open('path/to/my/file') as myFile:
for line in myFile.readlines():
print line
And straight from the documentation themselves, from at least Python 3.5 to 3.7,
If you want to read all the lines of a file in a list you can also use
list(f)
orf.readlines()
.
Upvotes: 1
Reputation: 8244
split()
splits by any whitespace. Use this:
file = open("text.txt")
strings = [line.strip() for line in file]
Upvotes: 3