How can I create files in python.

How do I create a whole new file in python, a .txt file to be specific.

I know about opening and writing existing files so please don’t tell me how to do that (thats what google told me to do :frowning: ), unless it somehow makes a new file, then sure.

Try:


from __future__ import with_statement

with open('somefile.txt', 'w') as f:
    f.write('some stuff')

Depending on Python version you are using you may or may not need the first import. Note that with closes the file handle so you don’t have to check for this separately unlike before.

Thanks for that, it works fine. I do need to import the with_statement. Is it newer or older versions where I don’t need to do the import?

with statement has been included to Python 2.6 by default. See http://docs.python.org/whatsnew/2.6.html#pep-343-the-with-statement for more information about it.