Home » Python » How do I check if a file exists with * in python?-Exceptionshub

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

Posted by: admin February 24, 2020 Leave a comment

Questions:

I’m trying to check if a file exists so I can read it. The kicker is I don’t know what the number on the file is. Only one file should exist at a time, but the name updates as I write to the file (in another part of the code) so I don’t know exactly what the number will be when this chunk of code executes.

N=0
if os.path.exists('*somefile.txt'): #if the file exists, read it
    print("found Nsomefile.txt")
    filename = '*somefile.txt'
    something=np.loadtxt(filename)
    N = int(filename.split('s')[0]) #save the N from the filename
else: #otherise, preallocate memory for something
    something = np.empty((x,y))  
print(N,"of some thing")

In my directory I can see the file there (’32somefile.txt’) but the code still prints
0 of some thing

How to&Answers:

You can use glob() from pathlib.

https://docs.python.org/3.5/library/pathlib.html#methods-and-properties

Answer:

You should probably use glob rather than os functions here.

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