Reading about Python? Actually practice it. Try PyChallenge free

Python Tutorial

Write file

Python hosting: PythonAnywhere — host, run and code Python in the cloud. Free tier available.

Python supports writing files by default, no special modules are required. You can write a file using the .write() method with a parameter containing text data.

Before writing data to a file, call the open(filename,'w') function where filename contains either the filename or the path to the filename. Finally, don't forget to close the file.

Related Course:
Practice Python with interactive exercises

Create file for writing

The code below creates a new file (or overwrites) with the data.

#!/usr/bin/env python

# Filename to write filename = "newfile.txt"

# Open the file with writing permission myfile = open(filename, 'w')

# Write a line to the file myfile.write('Written with Python\n')

# Close the file myfile.close()

The 'w' flag makes Python truncate the file if it already exists. That is to say, if the file contents exists it will be replaced.

Append to file

If you simply want to add content to the file you can use the 'a' parameter.

#!/usr/bin/env python

# Filename to append filename = "newfile.txt"

# The 'a' flag tells Python to keep the file contents # and append (add line) at the end of the file. myfile = open(filename, 'a')

# Add the line myfile.write('Written with Python\n')

# Close the file myfile.close()

Parameters

A summary of parameters:
BackNext
Practice
Stop reading. Start writing Python.
PyChallenge gives you interactive exercises in your browser — no install needed.
Practice Python with interactive exercises
Flag Action
r Open file for reading
w Open file for writing (will truncate file)
b binary more
r+ open file for reading and writing
a+ open file for reading and writing (appends to end)
w+ open file for reading and writing (truncates files)