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

时间:2013-08-30 13:04:11

标签: python file python-3.x file-io

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

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

7 个答案:

答案 0 :(得分:115)

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

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

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

答案 1 :(得分:6)

而不是使用try-except块,你可以使用if else

如果文件不存在,

将无法执行,     开放(名称,' R +&#39)

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

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

' W'如果非exis

,则创建一个文件

答案 2 :(得分:6)

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

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

答案 3 :(得分:3)

这很好用,但不是

name = input('Enter name of text file: ')+'.txt' 

你应该使用

name = raw_input('Enter name of text file: ')+'.txt'

一起
open(name,'a') or open(name,'w')

答案 4 :(得分:1)

import sys

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

    name = raw_input('Enter name of text file: ')+'.txt'  # Name of text file coerced with +.txt

    try:
        file = open(name,'a')   # 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()

这将有效:)

答案 5 :(得分:1)

为简单起见,您可以使用os.system函数:

import os
os.system("touch filename.extension")

这会调用系统终端来完成任务。

答案 6 :(得分:0)

您可以使用open(name, 'a')

但是,输入文件名时,请在两侧使用引号,否则".txt"无法添加到文件名