Write file functionality is part of the standard module, you don’t need to include any modules.
Writing files and appending to a file are different in the Python language.
You can open a file for writing using the line
f = open("test.txt","w")
to append to a file use:
f = open("test.txt","a")
If you specify the wrong parameter, your file could be emptied!
Related course: Complete Python Bootcamp: Go from zero to hero in Python 3
To create new files, you can use this code:
The ‘\n’ character adds a new line. If the file already exists, it is replaced. If you use the “w” parameter, the existing contents of the file will be deleted.
To add text to the end of a file, use the “a” parameter.
- Write the text “Take it easy” to a file
- Write the line open(“text.txt”) to a file