6

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

5 Answers 5

6

You don't use line, try:

with open('data.txt') as f:
    for line in f:
        print line
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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)

Comments

1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.