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

发布于 2021-01-29 15:10:02

此功能无效,并引发错误。我是否需要更改任何参数或参数?

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()
关注者
0
被浏览
56
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    如果文件不存在,open(name,'r+')将失败。

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

    另外,您可以使用open(name, 'a'); 如果该文件不存在,则会创建该文件,但不会截断现有文件。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看