Reputation: 9
I have a file with different planets written on each line. I'm trying to iterate through it using the with function and print so the the output looks like this:
1 - mercury
2 - venus
etc...
but my output currently looks like this:
(1, '-', <open file 'planets.txt', mode 'r' at 0x7f87dea69660>)
(2, '-', <open file 'planets.txt', mode 'r' at 0x7f87dea69660>)
(3, '-', <open file 'planets.txt', mode 'r' at 0x7f87dea69660>)
(4, '-', <open file 'planets.txt', mode 'r' at 0x7f87dea69660>)
my code is this:
with open("planets.txt") as p:
i=0
for line in p:
i += 1
print(i, '-', p)
How am I using with wrong or is it something else?
Upvotes: 0
Views: 53
Reputation: 411
Instead of printing the line
you print p
- the file itself:
print(i, '-', p)
Also, instead of making a new variable to count lines, you may use enumerate feature:
with open("planets.txt") as p:
for i, line in enumerate(p, 1):
print(i, '-', line)
UPD: You should also consider the fact, that the line
you are getting from the file ends with a newline character and when you print(line)
it adds another newline after it by defaulf. So your output will look like that:
1 - mercury
2 - venus
etc...
to get
1 - mercury
2 - venus
etc...
you need to specify end=''
argument to print function. This way:
print(i, '-', line, end='')
Upvotes: 1
Reputation: 19264
You want to print line
not p
:
with open("planets.txt") as p:
i=0
for line in p:
i += 1
print(i, '-', line) #refers to each line in p rather than the file handler
Upvotes: 0