Reputation: 85
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
Upvotes: 0
Views: 1964
Reputation: 243
You can use glob() from pathlib.
https://docs.python.org/3.5/library/pathlib.html#pathlib.Path.glob
Upvotes: 4
Reputation: 85
Thanks everyone! I forgot about glob. (I use it in another part of my code (facepalm)). It now looks like:
import numpy as np
from glob import glob
N=0
if glob('*somefile.txt'): #if the file exists, read it
print("found Nsomefile.txt")
filename = glob('*somefile.txt')[0]
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")
which outputs
found Nsomefile.txt
32 of some thing
Upvotes: 0
Reputation: 281
You should probably use glob rather than os functions here.
Glob also supports * characters, so it should do fine for your use case.
Upvotes: 2