Richard Lewis
Richard Lewis

Reputation: 31

Split lines in .txt file in Python

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

Answers (3)

taras
taras

Reputation: 6915

Just use

strings = strings.splitlines()

instead of

strings = strings.split()

The splitlines method splits a string by newline characters.

Upvotes: 0

David Culbreth
David Culbreth

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) or f.readlines().

Upvotes: 1

Markus Unterwaditzer
Markus Unterwaditzer

Reputation: 8244

split() splits by any whitespace. Use this:

file = open("text.txt")
strings = [line.strip() for line in file]

Upvotes: 3

Related Questions