2013-08-30 44 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