I am looking for a simple way to extract the extension (.txt, .py, .jl, etc) from a file in Julia. I looked through the Julia docs but didn't see anything specifically built for this.
How to extract the extension from a filename in Julia?
It’s OK to Ask and Answer Your Own Questions: stackoverflow.blog/2011/07/01/… –
Ashlaring
It absolutely is. People get so upset about that sometimes, but it really is very much in line with the goals of the site as a whole. –
Aged
Use splitext
from Filesystem
julia> splitext("/home/myuser/example.jl")
("/home/myuser/example", ".jl")
julia> splitext("/home/myuser/example")
("/home/myuser/example", "")
This is a faster alternative, if that is of any importance:
file_extension(file::String) = file[findlast(==('.'), file)+1:end]
While there is no built in Julia function to do this, what you can do is given the filename, split the string on a period "." as follows:
julia> filePath = "some/path/my_program.jl"
"some/path/my_program.jl"
julia> split(filePath, ".")[2]
"jl"
I would use
split(filePath, ".")[end]
to be sure to get the file extension.. –
Negus This fails when there are dots in the file path.
end
is indeed the best solution. –
Catholicon © 2022 - 2024 — McMap. All rights reserved.