Reputation: 25
So I have read/printed out 2 lines from a file but there is a gap in between them but I want to but both of them beside each other , how do I do that.
if GTIN == '86947367':
fp = open("read_it.txt")
for i, line in enumerate(fp):
if i == 1:
print(line)
elif i == 2:
print(line)
fp.close()
When I run this it gives an output of:
banana
(space)
(space)
5.00
I wanna put both print(line)
besides each other to give an output of:
banana 5.00
TEXT FILE:
86947367
banana
5.00
78364721
apple
3.00
35619833
orange
2.00
84716491
sweets
8.00
46389121
chicken
10.00
74937462
Upvotes: 0
Views: 94
Reputation: 85442
This:
with open("read_it.txt") as fp:
next(fp)
print(next(fp).rstrip(), next(fp))
prints:
banana 5.00
First you open the file with promise to close it with open("read_it.txt") as fp:'
. Now you use next(fp)
to skip the first line. Finally, you print the content of both lines. You need to strip the newline character at the end of the first printed line with .rstrip()
.
Your file object fp
is a so called iterator. That means next(fp)
gives you the next line.
This would work, if you want to print the output for your GTIN
:
with open("read_it.txt") as fp:
GTIN = '86947367'
show = False
for line in fp:
if not line.strip():
show = False
continue
if line.strip() == GTIN:
show = True
continue
if show:
print(line.rstrip(), end=' ')
prints:
banana 5.00
Upvotes: 1
Reputation: 2040
with open("read_it.txt") as f: print(' '.join([f.readline().rstrip() for x in range(3)][1:]))
Upvotes: 0