用python创建一个新的文本文件时出错? [英] Error when creating a new text file with python?

查看:138
本文介绍了用python创建一个新的文本文件时出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  import sys 

def write():
print('Creating new text file ')

name = input('输入文本文件的名字:')+'。txt'#强制使用+ .txt的文本文件的名字

try:
file = open(name,'r +')#试图创建一个新文件或者打开一个文件
file.close()

除了:
print('Something went )
sys.exit(0)#quit Python

write()
open(name,'r +') 您可以使用 open(name,'w')来创建文件如果文件不存在,但会截断现有文件。



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

This function doesn't work and raises an error. Do I need to change any arguments or parameters?

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()

解决方案

If the file does not exists, open(name,'r+') will fail.

You can use open(name, 'w'), which creates the file if the file does not exist, but it will truncate the existing file.

Alternatively, you can use open(name, 'a'); this will create the file if the file does not exist, but will not truncate the existing file.

这篇关于用python创建一个新的文本文件时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆