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()
Use the open() function with the 'w' or 'x' mode to create a new text file.
Errors will always arise when working with files that are missing. Python may fail to retrieve a file, if you have written the wrong spelling of the filename, or the file does not exist.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With