re.match不接受txt文件格式

时间:2014-12-30 08:06:04

标签: python regex

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.match

2 个答案:

答案 0 :(得分:2)

你应该逃脱第二个点并且不要使用“t”字符:

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

另请注意,您实际上并不需要正则表达式,只需使用endswith或搜索可以为您提供文件扩展名的模块:

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

fileExtension.txt,这正是您正在寻找的。

答案 1 :(得分: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,你可以使用更加pythonic的if thing :

相关问题