[英]How do I check if a file exists with * in python?
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
在我的目录中,我可以看到那里的文件 ('32somefile.txt') 但代码仍然打印0 of some thing
You can use glob() from pathlib.您可以使用 pathlib 中的 glob()。
https://docs.python.org/3.5/library/pathlib.html#pathlib.Path.glob https://docs.python.org/3.5/library/pathlib.html#pathlib.Path.glob
You should probably use glob rather than os functions here.您可能应该在这里使用 glob 而不是 os 函数。
Glob also supports * characters, so it should do fine for your use case. Glob 还支持 * 字符,因此它应该适合您的用例。
Thanks everyone!谢谢大家! I forgot about glob.我忘记了 glob。 (I use it in another part of my code ( facepalm )). (我在代码的另一部分( 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.