Writing files is easy: Python has built in support for writing files. In this article we’ll show you how to write data to a file.

To write a file, we must first open it. We can open the file with method open(filename, flag). The flag needs to be ‘w’, short for write.

Related Course: Complete Python Programming Course & Exercises

Write file example code

We call the method open, then we write strings using the method write(). This is similar to how you would write files in other programming languages. Then we close the file.

To write files, you can use this code:

#!/usr/bin/env python

f = open("output.txt","w")
f.write("Pythonprogramminglanguage.com, \n")
f.write("Example program.")
f.close()
On the first line we open the file for writing. The parameter "w" tells Python we want to open the file for writing.

The write() calls write data into the file.
Finally we close the file with the .close() method call.

python write text file

Write list to file

A list can be written directly into a file.
We do that by:

  • Define list
  • Open file
  • Write list elements using for loop
    In code that’s:
#!/usr/bin/env python

europe = [ 'Netherlands','Belgium','France','Germany','Danmark' ]

mfile = open('europe.txt', 'w')
for country in europe:
mfile.write("%s\n" % country)

Download exercises