Reputation: 931
I am a beginner and just started learning Python couple days ago (yay!)
so i've come across a problem. when i run, this code outputs everything but the text (txt in file is numbers 0-10 on seperate lines)
def output():
xf=open("data.txt", "r")
print xf
print("opened, printing now")
for line in xf:
print(xf.read())
print("and\n")
xf.close()
print("closed, done printing")
Upvotes: 6
Views: 284
Reputation: 1676
The reason you aren't seeing the line output is because you aren't telling it to output the line. While iterating over values of line
, you print xf.read()
. The following is your function rewritten with this in mind. Also added is the use of a with statment block to automatically close the file when you're done with it.
(Using xf.close()
is not wrong, just less pythonic for this example.)
def output():
with open("data.txt", "r") as xf:
print xf
print("opened, printing now")
for line in xf:
print(line)
print("and\n")
print("closed, done printing")
Upvotes: 1
Reputation: 64225
This should print out each number on its own line, like you want, in a lot less code, and more readable.
def output():
f = open('data.txt', 'r').read()
print f
Upvotes: 2
Reputation: 32710
You have read the line of text into the variable line in the code for line in xf:
so you need to show that e.g. print(line)
I would look at tutorials like the python.org one
Upvotes: 0
Reputation: 165340
When you used for line in xf:
you basically already iterated over the file, implicitly reading each line.
All you need to do is print it:
for line in xf:
print(line)
Upvotes: 1
Reputation:
You don't use line
, try:
with open('data.txt') as f:
for line in f:
print line
Upvotes: 6