此函数不起作用并引发错误。我需要更改任何参数或参数吗?
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')
;如果文件不存在,这将创建文件,但不会截断现有文件。
关于python - 使用python创建新文本文件时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18533621/