69

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()
4
  • When writing a question, always be sure to state what doesn't work. Is there a syntax error? Does it crash? Does it do something, but not what you intended? Ideally, give us the expected outcome and the actual outcome. "Doesn't work" is too vague. Commented Aug 30, 2013 at 13:10
  • 15
    Get rid of that harmful "exception handling" block that only prevents you from knowing exactly what went wrong. Commented Aug 30, 2013 at 13:23
  • +1 @brunodesthuilliers ! What he means is don't write such generic except blocks. If you are unsure what exceptions are, remove the exception handling and test, you will at least know what's going wrong. Commented Dec 10, 2015 at 5:15
  • 1
    Out of curiosity, what does open() even do? I've read the answers below and got it working, although I chose to go with 'a+' rather than 'r+' simply because I have a record keeping application in mind. But now that it's working, how do I actually append data? And where exactly is the file I'm creating? ---To specify what 'working' means, I receive as output the following line: <_io.TextIOWrapper name='hello' mode='a+' encoding='cp1252'> Commented Apr 6, 2016 at 15:13

7 Answers 7

114

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.

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

3 Comments

Neither "w" or "a" creates a new file for me.
Stupid me didn't add the directory Desktop in my path, so I was sitting there missing a part of the file path. . .
to avoid modifying an existing file, 'x' could be used instead of 'w', 'a'.
6

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

Comments

6

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

import sys
def 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()

2 Comments

Thanks for your answer but sadly doesn't work for me as "error occurred"!!
Not following PEP. Using different indentation. Incorrectly handling exception.
3

This works just fine, but instead of

name = input('Enter name of text file: ')+'.txt' 

you should use

name = raw_input('Enter name of text file: ')+'.txt'

along with

open(name,'a') or open(name,'w')

2 Comments

The question is marked as python-3.x in which raw_input is not available.
Tag python-3.x was added after this answer
1
import sys

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

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

    try:
        file = open(name,'a')   # 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()

this will work promise :)

2 Comments

Does this add anything that didn't already exist in the 2 year old answers above?
He changed name=input() to name=raw_input(). Of course, that's deprecated.
1

You can os.system function for simplicity :

import os
os.system("touch filename.extension")

This invokes system terminal to accomplish the task.

1 Comment

one of the best things about python is the stdlib abstracts away OS specific utility calls such as touch... best to avoid something like this at all costs
0

You can use open(name, 'a')

However, when you enter filename, use inverted commas on both sides, otherwise ".txt"cannot be added to filename

2 Comments

it looks like the previous answer already mentioned open(name, 'a'), so it would have been better to just add your last line as a comment
"Inverted commas"? Do you mean single quotes? Python doesn't care whether you enclose a string in single quotes or double quotes. It only matters if the string includes a matching delimiter; enclosing it in the other kind can save having to escape the enclosed character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.