python write to file
Python hosting: Host, run, and code Python in the cloud!
Python supports writing files by default, no special modules are required. You can write a file using the .write() method with a parameter containing text data.
Before writing data to a file, call the open(filename,’w’) function where filename contains either the filename or the path to the filename. Finally, don’t forget to close the file.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Create file for writing
The code below creates a new file (or overwrites) with the data.
#!/usr/bin/env python |
The ‘w’ flag makes Python truncate the file if it already exists. That is to say, if the file contents exists it will be replaced.
Append to file
If you simply want to add content to the file you can use the ‘a’ parameter.
#!/usr/bin/env python |
Parameters
A summary of parameters:
Flag | Action |
---|---|
r | Open file for reading |
w | Open file for writing (will truncate file) |
b | binary more |
r+ | open file for reading and writing |
a+ | open file for reading and writing (appends to end) |
w+ | open file for reading and writing (truncates files) |
Leave a Reply: