Created
March 25, 2017 19:28
-
-
Save keithweaver/4716b88f0b6e3e17577a819f42d348db to your computer and use it in GitHub Desktop.
Write to File with 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
# Writing to a file in Python | |
# This was tested on Python 2.7. | |
# path - is a string to desired path location. The file does | |
# not have to exist. | |
# content - is a string with the file content. | |
def writeToFile(path, content): | |
file = open(path, "w") | |
file.write(content) | |
file.close() | |
PATH_TO_MY_FILE = './example.txt' | |
CONTENT_FOR_MY_FILE = 'Example\nThis is on line 2 of a text file.\n\nThe end.' | |
writeToFile(PATH_TO_MY_FILE, CONTENT_FOR_MY_FILE) | |
# Run in terminal using: | |
# python write-to-file.py | |
# | |
# It will create a file called `example.txt` and the contents will look like (minus the number signs): | |
# Example | |
# This is on line 2 of a text file. | |
# | |
# The end. |
`# Writing to a file in Python
This was tested on Python 2.7.
path - is a string to desired path location. The file does
not have to exist.
content - is a string with the file content.
def writeToFile(path, content):
file = open(path, "w")
file.write(content)
file.close()
PATH_TO_MY_FILE = './example.txt'
CONTENT_FOR_MY_FILE = 'Example\nThis is on line 2 of a text file.\n\nThe end.'
writeToFile(PATH_TO_MY_FILE, CONTENT_FOR_MY_FILE)
Run in terminal using:
python write-to-file.py
It will create a file called example.txt
and the contents will look like (minus the number signs):
Example
This is on line 2 of a text file.
The end.
`
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This should work in Python 3 as well, but in Python 3, it is better to use
with
syntax, since you do not have to explicitly close the file: