Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File creation in Python

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?

like image 703
Nathan2055 Avatar asked Feb 17 '26 02:02

Nathan2055


2 Answers

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.

like image 97
abarnert Avatar answered Feb 18 '26 15:02

abarnert


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.

like image 23
Platinum Azure Avatar answered Feb 18 '26 16:02

Platinum Azure



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!