Skip to content

Instantly share code, notes, and snippets.

@keithweaver
Created March 25, 2017 19:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keithweaver/4716b88f0b6e3e17577a819f42d348db to your computer and use it in GitHub Desktop.
Save keithweaver/4716b88f0b6e3e17577a819f42d348db to your computer and use it in GitHub Desktop.
Write to File with Python
# 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.
@PlaceReporter99
Copy link

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:

def writeToFile(path, content):
  with open(path, "w") as file:
    file.write(content)

@sumansingh777
Copy link

`# 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