Created
December 7, 2012 22:56
-
-
Save buchanae/4237214 to your computer and use it in GitHub Desktop.
Writing to a file (python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is my preferred way to use print | |
# and makes my code compatible with future versions | |
# of python. More info here: | |
# http://docs.python.org/2/library/functions.html#print | |
from __future__ import print_function | |
# http://docs.python.org/2/library/functions.html#open | |
# http://effbot.org/zone/python-with-statement.htm | |
with open('output.txt', 'w') as file_handle: | |
# notice I didn't add a newline at the end, print() does that for you | |
print('line', file=file_handle) | |
# The "with" statement above isn't necessary, and it's a more advanced style, | |
# but in my opinion it's a more pythonic style. | |
# Here's how you'll see it most often, without the "with" statement. | |
file_handle = open('output.txt', 'w') | |
print('line', file=file_handle) | |
# This line isn't exactly necessary, python will usually do it automatically, | |
# and I usually leave it out, but many people recommend it as one of those | |
# "safer" things to do. | |
# The "with" statement above automatically closes the file, so this is unnecessary there. | |
file_handle.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment