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.
Complete Python Bootcamp: Go from zero to hero in Python
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:
f = open("output.txt","w")
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:
- Define list
- Open file
- Write list elements using for loop
In code that’s:
europe = [ 'Netherlands','Belgium','France','Germany','Danmark' ]
mfile = open('europe.txt', 'w')
for country in europe:
mfile.write("%s\n" % country)