我正在尝试检查文件是否存在,以便我可以读取它。更重要的是,我不知道文件号是多少。一次只能存在一个文件,但是名称在我写入文件时会更新(在代码的另一部分中),因此我不知道执行此代码块时确切的数字。
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")
在我的目录中,我可以在那里看到文件('32somefile.txt'),但代码仍会打印0 of some thing
您可能应该在这里使用glob而不是os函数。
Glob还支持*字符,因此应适合您的用例。
您可以使用pathlib中的glob()。
https://docs.python.org/3.5/library/pathlib.html#methods-and-properties
谢谢大家!我忘了世界。 (我将其用于代码的另一部分(facepalm))。现在看起来像:
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")
输出]
found Nsomefile.txt
32 of some thing