【问题标题】:Check for valid file extension检查有效的文件扩展名
【发布时间】:2016-09-11 00:13:20
【问题描述】:

在用户输入时,我试图验证他们输入了适当的文件扩展名。例如:

file1 = input('Enter the file name ending in ".txt": ')

我想验证他们是否输入了“.txt”。现在我正在做非常基本的检查。但是,下面的检查并不能真正验证文件是否以 .txt 结尾。

if '.txt' not in file_name:
    print('Include file extension (example): ".txt"')

所以我认为它在 '.' 之后只存在验证 'txt' 字符。但前提是那是最后的 '.',例如,我不希望它意外捕获 baby.dinosoars.txt 中的“dinosoars”。

【问题讨论】:

标签: validation python-3.x


【解决方案1】:

如果你把你的文件名变成一个字符串s,你可以使用endswith:

if s.endswith('.txt'):
...
elif s.endswith('.test'):
...

或不区分大小写的版本(并消除任何 else-if 链)

s.lower().endswith(('.png', '.jpg', '.jpeg'))

【讨论】:

    【解决方案2】:

    为什么不改用endswith

    if not file_name.endswith(extension):
        #exec code
    

    【讨论】:

      【解决方案3】:

      这应该可行:

      if file_name.endswith(".txt"):
          print "something"
      

      【讨论】:

      • endswith 而不是 ends_withprint 在 Python 3.x 中需要括号
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 2018-05-29
      • 1970-01-01
      相关资源
      最近更新 更多