2013-08-30 43 views
66

此功能不起作用并引发错误。我是否需要更改任何参数或参数?使用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() 
+0

当写一个问题,始终确保州* *什么不起作用。有语法错误吗?它会崩溃吗?它做了什么,但不是你想要的?理想情况下,给我们预期的结果和实际结果。 “不起作用”太模糊。 – chepner

+13

摆脱有害的“异常处理”块,只会阻止您明确知道哪里出了问题。 –

+0

+1 @brunodesthuilliers!他的意思是不要写这样的通用块,除非块。如果您不确定什么是异常,请删除异常处理和测试,您至少知道发生了什么问题。 – 0xc0de

回答

110

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

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

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

+2

“w”或“a”都不会为我创建一个新文件。 – KI4JGT

+0

@ KI4JGT,你有什么错误吗? – falsetru

+0

愚蠢的我没有在我的路径中添加目录桌面,所以我坐在那里缺少文件路径的一部分。 。 。 – KI4JGT

0

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

但是,当你输入文件名,两侧使用引号,否则".txt"不能被添加到文件名

+2

它看起来像前面提到的答案已公开(名称,'a'),所以最好只是将最后一行添加为注释 – mc110

+5

“倒置逗号”?你的意思是*单引号*? Python不关心你是用单引号还是双引号括起一个字符串。只有当字符串包含匹配的分隔符时才重要;用另一种封闭它可以避免不必要的附加字符。 –

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') 
+7

该问题被标记为'python-3.x',其中'raw_input'不可用。 – falsetru

+10

在此答案后添加了标签'python-3.x' –

5

,而不是使用try-except块一起,你可以使用,如果其他

如果该文件是不存在的,这将不执行, 开放的(名字, 'R +')

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

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

'W' 创建一个文件,如果其非EXIS

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

这将活像ķ承诺:)

+1

这是否添加了上述2年前答案中不存在的任何内容? –

+0

他将'name = input()'改为'name = raw_input()'。当然,这是不赞成的。 – Musixauce3000

2

您可以使用os.system功能简单:

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

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

+5

关于python的最好的东西之一是stdlib提取操作系统特定的实用程序调用,如触摸......最好避免这样的代价不惜一切代价 – f0ster

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

感谢您的回答,但可悲的是不适合我作为“发生错误” ! –

+0

不遵循PEP。使用不同的缩进。错误地处理异常。 – Desprit