I have been reviewing the tutorial for file management in Python 3 but it doesn't mention how to create a file if one doesn't exist. How can I do that?
Just open the file in w mode, and it will be created it.
If you want to open an existing file if possible, but create a new file otherwise (and don't want to truncate an existing file), read the paragraph in your link that lists the modes. Or, for complete details, see the open reference docs. For example, if you want to append to the end instead of overwriting from the start, use a.
Just open the file in write mode:
f = open('fileToWrite.txt', 'w')
Note that this will clobber an existing file. The safest approach is to use append mode:
f = open('fileToWrite.txt', 'a')
As mentioned in this answer, it's generally better to use a with statement to ensure that the file is closed when you have finished with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With