2014-12-30 29 views
0
import os.path 
import re 
def request(): 
    print ("What file should I write to?") 
    file = input() 
    thing = os.path.exists (file) 
    if thing == True: 
     start = 0 
    elif re.match ("^.+.\txt$", file): 
     stuff = open (file, "w") 
     stuff.write ("Some text.") 
     stuff.close() 
     start = 0 
    else: 
     start = 1 
    go = "yes" 
    list1 = (start, file, go) 
    return list1 
start = 1 
while start == 1: 
    list1 = request() 
    (start, file, go) = list1 

拿起每當我進入Thing.txt作爲文本,該elif應該抓住,它在給定的格式。但是,start不會更改爲0,並且不會創建文件。我是否錯誤地格式化了re.matchre.match不上的txt文件格式

+2

'if file.endswith('txt')'解決你的正則表達式問題。 –

回答

2

"^.+.\txt$"是匹配了不正確的模式.txt文件,您可以使用下面的正則表達式:

r'^\w+\.txt$' 

由於\w單詞字符匹配,如果你想要的文件名只包含字母,你可以使用[a-zA-Z]代替:

r'^[a-zA-Z]+\.txt$' 

請注意,您需要轉義.,因爲它是正則表達式中的特殊符號。

re.match (r'^\w+\.txt$',file) 

但作爲一個備選答案的匹配文件名用特殊的格式,你可以使用endswith()

file.endswith('.txt') 

也代替if thing == True你可以使用if thing :這是更Python!

2

你應該逃脫第二點和反轉義的「T」字:

re.match ("^.+\.txt$", file) 

還要注意的是,你並不真正需要的正則表達式這一點,你可以簡單地使用endswith或搜索模塊,可以給你文件擴展名:

import os 
fileName, fileExtension = os.path.splitext('your_file.txt') 

fileExtension.txt,這是你在尋找什麼。