1

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
  • If you open(filename, 'w'), that will create a new file (or overwrite an existing one). Commented Nov 20, 2014 at 14:18
  • 1) Use 4-space indentation. 2) it is weird that isfile(path) == False implicates makedirs(path). 3) Opening a file for writing creates the file if it does not exist yet. At least, this is how most operating systems behave, and this is how Python behaves on any supported platform. Commented Nov 20, 2014 at 14:25

2 Answers 2

2

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'

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.