2
handle = open('full path/file name.txt')

file = handle.read()
print file

for line in handle:
    print line
  1. print file prints correctly
  2. print line does not return anything. No errors reported either. What am I doing wrong here?
1
  • 4
    After you .read the file you're already at the end, so there are no more lines in handle. Commented May 5, 2017 at 22:32

4 Answers 4

1

Once you read the file (handle.read()) the file reached its end, and so, when trying to iterate it again, it has nothing to provide anymore.

If you want to use use its contents again, you can either store them in the first read and use the stored content each time, or reset to the beginning of the file using seek:

handle.seek(0)
Sign up to request clarification or add additional context in comments.

Comments

0

You need to write from the read data, handle is a file object.

for line in file:
    print(line)

2 Comments

This would give each character, not each line. Also note that triple-backtick code fencing is for GitHub-flavour markdown, which SO doesn't support.
file = handle.readlines() ...I didnt fully read the persons code. good catch
0

The first point to note is that your for loop as it is right now will not get you the behaviour you are looking for. You need to have file = handle.readlines() instead of .read(). Otherwise, it would print each character on a new line, instead of each line. (Note that handle.readlines() returns a list, and so the print(file) line would now print that list.

Note also that after reading from the file using .read(), you would need to run handle.seek(0) to be able to print from that file again, as otherwise you will receive no output, as the 'reader' is at the end of the file.

1 Comment

"You should be reading from file instead." - no, because (despite the name) it's not a file, it's the content as a string. You can iterate over a file handle.
0

Below code should work for 2.7

handle = open('full path/file name.txt') file = handle.read()
handle.seek(0) print file

for line in handle:
    print line

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.