Reputation:
For each word in a txt file, I want to set x as the first word in the file and y as the second. I tried this for loop but am unsure what I need to put in the < >.
My file has two lines with each word on a newline.
for word in file:
x = <the first word>
y = <the second word>
Upvotes: 0
Views: 42
Reputation: 4313
with open('path/to/file.txt') as file:
x, y = [line.strip() for line in file]
Upvotes: 1
Reputation: 3070
Read line by line and decide which is what with an extra variable. This method is good for very large files, because it does not needs to load the entire file into memory:
with open('workfile') as f:
is_x = True
for word in file:
if is_x:
x = word
else:
y = word
do_things_on_x_and_y(x, y)
is_x = not is_x
Upvotes: 0
Reputation: 2524
My file has two lines with each word on a newline.
If it only has two lines then you could do this (no loop required):
x, y = file.read().splitlines()
Upvotes: 0