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

2024-04-25 14:53:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: of函数textnameimporttxtnew参数
3条回答

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

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

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

如果不使用try except块,您可以使用

如果文件不存在,则不会执行此操作, 打开(名称“r+”)

if os.path.exists('location\filename.txt'):
    print "File exists"

else:
   open("location\filename.txt", 'w')

如果文件不存在,则“w”将创建该文件

以下脚本将用于创建任何类型的文件,用户输入作为扩展名

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

相关问题 更多 >