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.

There is more to it than this one function. The Python Data I/O Mega Pack covers reading and writing files, csv, json, Excel and working with a database.

SQL is the language you use to ask a database questions. If you want to get better at it, SQLCrab runs real queries in the browser, nothing to install.

Python has writing files built in, there is nothing to install. The open function opens the file and the mode tells Python what you want to do with it.

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.

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)

The modes

  • 'w' write, creates the file and empties it if it already exists.
  • 'a' append, adds to the end and keeps what is already there.
  • 'x' write but only if the file does not exist, otherwise an error.
  • 'wb' and 'ab' are the binary versions.

Use a with block. It closes the file for you, also when an error happens in the middle:

with open('out.txt', 'w') as f:
    f.write('hello\n')

Writing text without a newline character puts everything on one long line. Use \n after each line.

Want more practice on this? Practise this on PyChallenge, there are short browser exercises you can run right after reading.