handle = open('full path/file name.txt')
file = handle.read()
print file
for line in handle:
print line
- print file prints correctly
- print line does not return anything. No errors reported either. What am I doing wrong here?
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)
You need to write from the read data, handle is a file object.
for line in file:
print(line)
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.
.readthe file you're already at the end, so there are no morelines inhandle.