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()
inbinder
  • 692
  • 4
  • 11
  • 28
Bython
  • 1,135
  • 1
  • 12
  • 21
  • 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. – chepner Aug 30 '13 at 13:10
  • 15
    Get rid of that harmful "exception handling" block that only prevents you from knowing exactly what went wrong. – bruno desthuilliers Aug 30 '13 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. – 0xc0de Dec 10 '15 at 05: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'>` – Musixauce3000 Apr 06 '16 at 15:13

7 Answers7

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.

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
falsetru
  • 357,413
  • 63
  • 732
  • 636
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

SriSreedhar
  • 409
  • 5
  • 6
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()
prathima
  • 113
  • 2
  • 9
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')
icedtrees
  • 6,134
  • 5
  • 25
  • 35
Ivan
  • 63
  • 1
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 :)

Daphnne
  • 116
  • 1
  • 1
  • 12
1

You can os.system function for simplicity :

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

This invokes system terminal to accomplish the task.

  • 7
    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 – f0ster Mar 08 '16 at 17:09
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

Pkarls
  • 35
  • 3
  • 18
  • 2
    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 – mc110 Jun 10 '14 at 08:18
  • 5
    "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. – Tom Zych Jun 28 '14 at 11:46