此函数不起作用并引发错误。是否需要更改任何参数或参数?
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')
,如果文件不存在,它将创建文件,但会截断现有文件。或者,您可以使用
open(name, 'a')
;如果文件不存在,这将创建文件,但不会截断现有文件。如果不使用try except块,您可以使用
如果文件不存在,则不会执行此操作, 打开(名称“r+”)
如果文件不存在,则“w”将创建该文件
以下脚本将用于创建任何类型的文件,用户输入作为扩展名
相关问题 更多 >
编程相关推荐