1 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊
loadtxt是一個(gè)相當(dāng)長(zhǎng)的函數(shù),但關(guān)于它的文件處理:
fown = False
try:
if isinstance(fname, os_PathLike):
fname = os_fspath(fname)
if _is_string_like(fname):
fh = np.lib._datasource.open(fname, 'rt', encoding=encoding)
fencoding = getattr(fh, 'encoding', 'latin1')
fh = iter(fh)
fown = True
else:
fh = iter(fname)
fencoding = getattr(fname, 'encoding', 'latin1')
except TypeError:
raise ValueError('fname must be a string, file handle, or generator')
...
try:
for x in read_data(_loadtxt_chunksize):
if X is None:
X = np.array(x, dtype)
else:
nshape = list(X.shape)
pos = nshape[0]
nshape[0] += len(x)
X.resize(nshape, refcheck=False)
X[pos:, ...] = x
finally:
if fown:
fh.close()
總之,如果你給它一個(gè)文件名(一個(gè)字符串),它會(huì)打開(kāi)它并注意到它owns是文件。實(shí)際的文件讀取和解析dtype受try/finally子句保護(hù)。如果它擁有該文件,則將其關(guān)閉。
因此,如果ValueError由于無(wú)法轉(zhuǎn)換為浮點(diǎn)數(shù)的字符串而得到 a,則不必?fù)?dān)心關(guān)閉文件。事實(shí)上,即使你想,你也做不到,因?yàn)槟銦o(wú)權(quán)使用fh手柄。
如果您希望您的代碼在此值錯(cuò)誤后執(zhí)行不同的操作,請(qǐng)將其包裝:
In [126]: try:
...: np.loadtxt(["1 2 two"])
...: except ValueError:
...: print('got a value error')
...:
got a value error
或修改您的main:
def main():
# Converts into a numpy array.
# loadtxt function has the default dtype as float
try:
x = np.loadtxt("wind.txt")
except ValueError:
print('error reading "wind.txt")
return # skips the rest
print("There are", len(x), "")
print('Average:', np.average(x))
print('Max:', np.amax(x))
print('Min:', np.amin(x))
file = open("testfile.txt", "w")
file.write(f"Amount: {len(x)}\n")
file.write(f"Average: {np.average(x)}\n")
file.write(f"Max: {np.amax(x)}\n")
file.write(f"Min: {np.amin(x)}\n")
file.close()
添加回答
舉報(bào)