Search code examples
pythonfilecreation

How to create a file (a text file as default if available) in python code


This is the code I have so far, yes I know the 'dirs' code creates a folder, but I am not sure of the code (if there is one) to create a file instead!

import os
if os.path.isfile(outfile):
 print("Name already used, please choose another")
else:
 os.makedirs(outfile)

Any help would be appreciated :D


Solution

  • Inorder to create a file and work on it, use the open() function.

    fp = open(outfile, mode)

    modes:

    r: read

    w: if file exists, replace it with a new one

    a: append existing file

    In your case the mode is 'w'