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.
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:
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.
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: