用python创build一个新的文本文件时出错?
此function不起作用并引发错误。 我是否需要更改任何参数或参数?
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()  如果文件不存在, open(name,'r+')将失败。 
 您可以使用open(name, 'w') ,如果该文件不存在,则会创build文件,但会截断现有文件。 
 另外,你可以使用open(name, 'a') ; 这将创build该文件,如果该文件不存在,但不会截断现有的文件。 
下面的脚本将用来创build任何types的文件,用户input作为扩展名
 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() 
而不是使用try-except块,否则可以使用
如果该文件不存在,则不执行,open(name,'r +')
 if os.path.exists('location\filename.txt'): print "File exists" else: open("location\filename.txt", 'w') 
如果文件不存在,'w'将创build一个文件
这工作得很好,但不是
 name = input('Enter name of text file: ')+'.txt' 
你应该使用
 name = raw_input('Enter name of text file: ')+'.txt' 
随着
 open(name,'a') or open(name,'w') 
你可以简单的os.system函数:
 import os os.system("touch filename.extension") 
这将调用系统terminal来完成任务。
 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() 
这将工作的承诺:)
 你可以使用open(name, 'a') 
 但是,input文件名时,请在两边使用反转逗号,否则".txt"不能添加到文件名