# Opening a file and printing its contents line by line

Everything that I've read online says that the best way to open a file in python is:

with open('<filename>') as f:
print line


That way you don't have to worry about forgetting to close the file. But I put this in an assignment in my python class and my professor marked points off saying that it was "VB style" (I have no idea what that means, Visual Basic style?) and that from now on I should open a file this way in python:

f=open('<filename>')
print line
f.close()


That seems messy to me and like you would run the risk of forgetting to close one of your files, but then again I'm just a student. What's the best way to open a file in Python?

• Oh, and to your question. You are right. Your professor is wrong. Mar 26 '17 at 2:42
• It's sad to see that someone teaching Python doesn't understand the value of Pythonic constructs. Mar 26 '17 at 8:45
• Personally, I think unsuitable questions from new users should be placed on hold or closed, but not repeatedly downvoted by more experienced users. Punishment for first attempts discourages new additions to the community. Mar 26 '17 at 18:25

Rather than using f.read().splitlines(), you can iterate the file object allowing you to use:

with open('<filename>') as f:
for line in f:
print line


Using with is better for various reasons, you don't have to remember to close the file, as you said in the question. It also closes the file, even if an error happened, which the second code doesn't. Take the following:

FILE_NAME = 'test_file.txt'
with open(FILE_NAME, 'w') as f:
f.write('Hello World')

f = open(FILE_NAME)
try:
with f:
raise Exception()
except Exception:
try:
except ValueError:
print 'I/O operation on closed file'

f = open(FILE_NAME)
try:
raise Exception()
except Exception:
try:
except ValueError:
print 'I/O operation on closed file'

f = open(FILE_NAME)
try:
try:
raise Exception()
finally:
f.close()
except Exception:
try:
except ValueError:
print 'I/O operation on closed file'


This outputs two I/O error messages and one 'Hello World'. The single hello world is using the second way, without a finally to close the file. And so if you did want to use the second method, then you'd want to use something like:

try:
f=open('<filename>')
for line in f:
print line
finally:
f.close()


And, we all know which is easier to read an write. For more information about the with statement you can look into PEP 343, which explains why it was added to Python.