【问题标题】:Error when creating a new text file with python?使用python创建新文本文件时出错?
【发布时间】:2013-09-03 05:24:35
【问题描述】:

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

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

【问题讨论】:

  • 写问题时,请务必说明什么不起作用。有语法错误吗?它会崩溃吗?它会做一些事情,但不是你想要的吗?理想情况下,给我们预期的结果和实际的结果。 “不起作用”太含糊了。
  • 摆脱有害的“异常处理”块,它只会让你无法确切知道出了什么问题。
  • +1 @brunodesthuilliers !他的意思是不要写这样的通用,除了块。如果你不确定异常是什么,去掉异常处理和测试,你至少会知道哪里出了问题。
  • 出于好奇,open() 甚至可以做什么?我已经阅读了下面的答案并得到了它的工作,尽管我选择使用“a+”而不是“r+”只是因为我有一个记录保存应用程序。但是现在它正在工作,我如何实际附加数据?我正在创建的文件到底在哪里? ---要指定“工作”的含义,我收到以下行作为输出:<_io.TextIOWrapper name='hello' mode='a+' encoding='cp1252'>

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


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答,但遗憾的是对我不起作用,因为“发生错误”!!
  • 不关注 PEP。使用不同的缩进。错误处理异常。
【解决方案2】:

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

但是,当你输入文件名时,两边都要使用引号,否则".txt"不能添加到文件名中

【讨论】:

  • 它看起来像前面已经提到的答案 open(name, 'a'),所以最好将最后一行添加为评论
  • “反逗号”?你的意思是单引号吗? Python 不关心你是用单引号还是双引号括起一个字符串。仅当字符串包含匹配的分隔符时才重要;将其包含在另一种类型中可以避免转义所包含的字符。
【解决方案3】:

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

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

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

【讨论】:

  • 关于 python 最好的事情之一是 stdlib 抽象出操作系统特定的实用程序调用,例如触摸......最好不惜一切代价避免这样的事情
【解决方案4】:
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()

这将起作用:)

【讨论】:

  • 这是否添加了上述 2 年旧答案中尚不存在的任何内容?
  • 他将name=input() 更改为name=raw_input()。当然,这已被弃用。
【解决方案5】:

除了使用 try-except 块,你可以使用 if else

如果文件不存在,这将不会执行, 打开(名称,'r+')

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

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

'w' 如果文件不存在则创建一个文件

【讨论】:

    【解决方案6】:

    这很好用,但不是

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

    你应该使用

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

    随着

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

    【讨论】:

    • 问题标记为python-3.x,其中raw_input不可用。
    • 标签python-3.x是在这个答案之后添加的
    【解决方案7】:

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

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

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

    【讨论】:

    • “w”或“a”都不会为我创建新文件。
    • 愚蠢的我没有在我的路径中添加目录桌面,所以我坐在那里缺少文件路径的一部分。 . .
    • 为避免修改现有文件,可以使用'x' 代替'w''a'
    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 2021-09-24
    • 2018-03-13
    • 2018-08-04
    • 2016-10-28
    相关资源
    最近更新 更多