检查字符串是否包含任何文件扩展名

时间:2018-04-06 09:10:07

标签: python python-3.x file-extension

我确定这是一件简单的事情,但我不知道如何做。我想要实现的是这样的:

templateFilename = str( templateFilename )

# If no file extension is found, assume it is a .npy file
if templateFilename.endswith( '.*' ):
    templateFilename += ".npy"

但是,这种语法似乎不起作用。我希望*代表任何文件扩展名,这样,如果解析的文件包含文件扩展名,那么将使用该文件扩展名,但如果没有,则会添加标准扩展名。

我已阅读有关glob模块的内容,人们似乎正在使用它来查找*.txt等内容,但我不确定它是如何工作的。

4 个答案:

答案 0 :(得分:2)

我建议export const GET_HOUNDS = 'my-awesome-app/hounds/LOAD'; export const GET_HOUNDS_SUCCESS = 'my-awesome-app/hounds/LOAD_SUCCESS'; export const GET_HOUNDS_FAIL = 'my-awesome-app/hounds/LOAD_FAIL'; export default function reducer(state = { hounds: [] }, action) { switch (action.type) { case GET_HOUNDS: console.log('Loading') return { ...state, loading: true }; case GET_HOUNDS_SUCCESS: console.log('Success') return { ...state, loading: false, hounds: action.payload.data }; case GET_HOUNDS_FAIL: console.log('failure') return { ...state, loading: false, error: 'Error while fetching hounds list' }; default: return state; } } export function listHounds(breed_name) { return { type: GET_HOUNDS, payload: { request: { url: `/api/breed/${breed_name}/images` } } }; } 。如果不存在,以下使用os.path.splitext作为扩展名:

.npy

答案 1 :(得分:0)

用法:

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"

答案 2 :(得分:0)

(从经验和脱发谈起)

.上进行拆分,然后选择第二个元素[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

答案 3 :(得分:0)

如果你想要一行,那么它就是:

templatefilename = "abcd"    
non_ext_file_list = [filename + ".npy" for filename in templateFilename.split(".") if not "." in templateFilename]

#output 
[abcd.npy]