使用python创建新文本文件时出错?

Byt*_*hon 69 python file-io file python-3.x

此功能不起作用并引发错误.我需要更改任何参数或参数吗?

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()
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 115

如果文件不存在,open(name,'r+')则会失败.

您可以使用open(name, 'w'),如果文件不存在,则会创建文件,但会截断现有文件.

或者,你可以使用open(name, 'a'); 如果文件不存在,这将创建文件,但不会截断现有文件.

  • "w"或"a"都不会为我创建新文件. (2认同)

小智 6

而不是使用try-except块,你可以使用,如果是的话

如果文件不存在,则不会执行,打开(名称,'r +')

if os.path.exists('location\filename.txt'):
    print "File exists"

else:
   open("location\filename.txt", 'w')
Run Code Online (Sandbox Code Playgroud)

如果非exis,'w'会创建一个文件


小智 6

以下脚本将用于创建任何类型的文件,用户输入作为扩展名

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()
Run Code Online (Sandbox Code Playgroud)