Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when creating a new text file with python?

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() 
like image 892
Bython Avatar asked Aug 30 '13 13:08

Bython


People also ask

How do you create a new text file in Python?

Use the open() function with the 'w' or 'x' mode to create a new text file.

Under what conditions can you fail to open a file for writing Python?

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.


1 Answers

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.

like image 199
falsetru Avatar answered Sep 19 '22 18:09

falsetru