python - Reading two strings from file -


i'm writing program in python , want compare 2 strings exist in text file , separated new line character. how can read file in , set each string different variable. i.e string1 , string2?

right i'm using:

file = open("text.txt").read(); 

but gives me content , not strings. i'm not sure returning text file contains 2 strings. tried using other methods such ..read().splitlines() did not yield result i'm looking for. i'm new python appreciated!

this reads first 2 lines, strips off newline char @ end, , stores them in 2 separate variables. not read in entire file first 2 strings in it.

with open('text.txt') f:     word1 = f.readline().strip()     word2 = f.readline().strip()  print word1, word2  # can compare word1 , word2 if 

text.txt:

foo bar asdijaiojsd asdiaooiasd 

output:

foo bar 

edit: make work number of newlines or whitespace:

with open('text.txt') f:     # sequence of words in lines     words = (word line in f word in line.split())     # consume first 2 items words sequence     word1 = next(words)     word2 = next(words) 

i've verified work reliably various "non-clean" contents of text.txt.

note: i'm using generator expressions lazy lists avoid reading more needed amount of data. generator expressions otherwise equivalent list comprehensions except produce items in sequence lazily, i.e. as asked.


Comments