daniel_e
daniel_e

Reputation: 257

Read first line of splitlines() file

I am having trouble converting this code snippet into reading only the first line of the file, rather than opening it random.

Can somebody help?

lines = open('myfile.txt').read().splitlines()
account =random.choice(lines)

Upvotes: 0

Views: 859

Answers (3)

Brad Solomon
Brad Solomon

Reputation: 40918

You could take advantage of the fact that the file object itself is iterable:

>>> with open('multiline.txt') as file:
...     line1 = next(file)

>>> line1
'this is line 1\n'

This doesn't waste memory by reading the entire file into a list.

However, I'd say @chepner's answer would be the "prescribed" way of doing this.

Upvotes: 2

chepner
chepner

Reputation: 531948

If you only want the first line, then only read the first line.

with open('myfile.txt') as f:
    line = f.readline()

Above, f.readline() reads until a newline or EOF.

Upvotes: 4

applesoup
applesoup

Reputation: 487

Starting from your code, you can simply change the second line to

first_line = lines[0]

and you are done.

Upvotes: 0

Related Questions