Error when creating a new text file with python?

Bython picture Bython · Aug 30, 2013 · Viewed 267.6k times · Source

This function doesn't work and raises an error. Do I need to change any arguments or parameters?

import sys

def write():
    print('Creating new text file') 

    name = input('Enter name of text file: ')+'.txt'  # Name of text file coerced with +.txt

    try:
        file = open(name,'r+')   # Trying to create a new file or open one
        file.close()

    except:
        print('Something went wrong! Can\'t tell what?')
        sys.exit(0) # quit Python

write()

Answer

falsetru picture falsetru · Aug 30, 2013

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.