How to Check Whether a File Exists Without Exceptions

How do I check whether a file exists without exceptions in Julia?

There are two simple ways of doing so.

First:

println(isfile("Sphere.jl"))
false

This isfile() function will simply check if the file exists. Note: if Sphere.jl is not in your current file path, you would need to provide the absolute path to get to that file.

Second (more of a trial by fire example):

try
open("Sphere.jl", "w") do s
println(s, "Hi")
end
catch
@warn "Could not open the file to write."
end

The second example utilizes the try-catch schema. It is always best for your program to not have to deal with errors so it's recommended that you use isfile() unless you have to use try-catch for your use case.

It's worth noting that there may be some cases where the file exists, but writing to it is not possible (i.e. it's locked by the os). In that case, using try-catch is a great option when attempting to write.

How do you check if a file exists or not?

You can use the os.path module to check if a file exists. The module is available for both Python 2 and 3.

import os.path

if os.path.isfile('filename.txt'):
print ("File exist")
else:
print ("File not exist")

How do I check if a file exists with * in python?

You should probably use glob rather than os functions here.

Glob also supports * characters, so it should do fine for your use case.



Related Topics



Leave a reply



Submit