Python

Write file

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 Courses Complete Python Bootcamp: Go from zero to hero in Python

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.

Write list to file

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

#!/usr/bin/env python

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

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

Previous Post Next Post

Cookie policy | Privacy policy | ©