Zerho
Zerho

Reputation: 1460

Python reading 2 strings from the same line

how can I read once at a time 2 strings from a txt file, that are written on the same line?

e.g. francesco 10

Upvotes: 0

Views: 1582

Answers (4)

Jakob Bowyer
Jakob Bowyer

Reputation: 34708

for line in fi:
    line.split()

Its ideal to just iterate over a file object.

Upvotes: 0

nmichaels
nmichaels

Reputation: 51029

'francesco 10'.split()

will give you ['francesco', '10'].

Upvotes: 0

Rafe Kettler
Rafe Kettler

Reputation: 76975

# out is your file
out.readline().split() # result is ['francesco', '10']

Assuming that your two strings are separated by whitespace. You can split based on any string (comma, colon, etc.)

Upvotes: 1

Marc B
Marc B

Reputation: 360882

Why not read just the line and split it up later? You'd have to read byte-by-byte and look for the space character, which is very inefficient. Better to read the entire line, and then split the resulting string on the space, giving you two strings.

Upvotes: 1

Related Questions