How to extract the extension from a filename in Julia?
Asked Answered
A

3

5

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.

Ashlaring answered 11/9, 2021 at 15:45 Comment(2)
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
A
16

Use splitext from Filesystem

julia> splitext("/home/myuser/example.jl") 
("/home/myuser/example", ".jl") 

julia> splitext("/home/myuser/example") 
("/home/myuser/example", "")
Archilochus answered 11/9, 2021 at 16:37 Comment(0)
A
1

This is a faster alternative, if that is of any importance:

file_extension(file::String) = file[findlast(==('.'), file)+1:end]
Aida answered 20/7, 2022 at 23:25 Comment(0)
A
0

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"

Ashlaring answered 11/9, 2021 at 15:45 Comment(2)
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.