检查字符串是否包含任何文件扩展名
Check if a string contains any file extension whatsoever
我确信这很容易做到,但我不知道怎么做。我想要实现的是这样的:
templateFilename = str( templateFilename )
# If no file extension is found, assume it is a .npy file
if templateFilename.endswith( '.*' ):
templateFilename += ".npy"
但是,这种语法似乎不起作用。我希望 *
代表任何文件扩展名,这样,如果解析的文件确实包含文件扩展名,则会使用该文件扩展名,但如果不包含,则会添加标准扩展名。
我已经阅读了 glob
模块,人们似乎正在使用它来查找 *.txt
等内容,但我不确定它是如何工作的。
用法:
file_extension = [".pyo", ".npy", ".py"]
templateFilename = str( templateFilename )
# If no file extension is found, assume it is a .npy file
if not templateFilename.split(".")[1] in file_extension:
templateFilename += ".npy"
我建议 os.path.splitext
。如果 none 存在,以下使用 .npy
作为扩展名:
root, ext = os.path.splitext(path)
if not ext:
ext = '.npy'
path = root + ext
(经验之谈hair-loss)
拆分.
然后选择第二个元素[1]
只有在绝对保证文件名中没有.
的情况下才有效;否则你需要这样的东西:
file_extension = [".csv", ".xml", ".html"]
if '.' in templateFilename: #checks if you can actually split, if you can't perform a split; you would raise an index error.
if templateFilename.split(".")[-1] in file_extension: #[-1] = the last element in the list.
has_extension = true
has_verified_extension = true
else:
has_extension = true
has_verified_extension = false
else: #no '.'. in the filename, so no extension.
has_extension = false
如果你想要一行,那么这里是:
templatefilename = "abcd"
non_ext_file_list = [filename + ".npy" for filename in templateFilename.split(".") if not "." in templateFilename]
#output
[abcd.npy]
我确信这很容易做到,但我不知道怎么做。我想要实现的是这样的:
templateFilename = str( templateFilename )
# If no file extension is found, assume it is a .npy file
if templateFilename.endswith( '.*' ):
templateFilename += ".npy"
但是,这种语法似乎不起作用。我希望 *
代表任何文件扩展名,这样,如果解析的文件确实包含文件扩展名,则会使用该文件扩展名,但如果不包含,则会添加标准扩展名。
我已经阅读了 glob
模块,人们似乎正在使用它来查找 *.txt
等内容,但我不确定它是如何工作的。
用法:
file_extension = [".pyo", ".npy", ".py"]
templateFilename = str( templateFilename )
# If no file extension is found, assume it is a .npy file
if not templateFilename.split(".")[1] in file_extension:
templateFilename += ".npy"
我建议 os.path.splitext
。如果 none 存在,以下使用 .npy
作为扩展名:
root, ext = os.path.splitext(path)
if not ext:
ext = '.npy'
path = root + ext
(经验之谈hair-loss)
拆分.
然后选择第二个元素[1]
只有在绝对保证文件名中没有.
的情况下才有效;否则你需要这样的东西:
file_extension = [".csv", ".xml", ".html"]
if '.' in templateFilename: #checks if you can actually split, if you can't perform a split; you would raise an index error.
if templateFilename.split(".")[-1] in file_extension: #[-1] = the last element in the list.
has_extension = true
has_verified_extension = true
else:
has_extension = true
has_verified_extension = false
else: #no '.'. in the filename, so no extension.
has_extension = false
如果你想要一行,那么这里是:
templatefilename = "abcd"
non_ext_file_list = [filename + ".npy" for filename in templateFilename.split(".") if not "." in templateFilename]
#output
[abcd.npy]