Error when creating a new text file with python? Error when creating a new text file with python? python-3.x python-3.x

Error when creating a new text file with python?


If the file does not exists, open(name,'r+') will fail.

You can use open(name, 'w'), which creates the file if the file does not exist, but it will truncate the existing file.

Alternatively, you can use open(name, 'a'); this will create the file if the file does not exist, but will not truncate the existing file.


instead of using try-except blocks, you could use, if else

this will not execute if the file is non-existent, open(name,'r+')

if os.path.exists('location\filename.txt'):    print "File exists"else:   open("location\filename.txt", 'w')

'w' creates a file if its non-exis


following script will use to create any kind of file, with user input as extension

import sysdef create():    print("creating new  file")    name=raw_input ("enter the name of file:")    extension=raw_input ("enter extension of file:")    try:        name=name+"."+extension        file=open(name,'a')        file.close()    except:            print("error occured")            sys.exit(0)create()