tags:

views:

97

answers:

5
+6  Q: 

Reading from file

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")  
+6  A: 

You don't use line, try:

with open('data.txt') as f:
    for line in f:
        print line
RC
+1  A: 

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)
Yuval A
A: 

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

Mark
+2  A: 

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
Zonda333
thank you thank you
pjehyun
+1  A: 

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") 
psicopoo