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

444 views Asked by At

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

2

There are 2 answers

0
T90 On BEST ANSWER

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'

0
Ludovic Viaud On

For create a file you can just open a file in write mode open('file.txt', 'w') https://docs.python.org/3/library/functions.html#open