为了账号安全,请及时绑定邮箱和手机立即绑定

做一个基本的TypeError?

做一个基本的TypeError?

呼唤远方 2022-07-12 10:30:44
我有这个读取风读数的基本程序,它按数量、最小值、最大值和平均值排序,然后用读数创建一个新文件。但是,我还希望它能够处理文件操作期间可能发生的任何异常,并确保文件始终关闭,即使发生异常也是如此。我对 python 和 numpy 很陌生,所以我正在寻求有关如何解决这个问题的帮助。我可能措辞错误。我希望错误处理这样做:如果 txt 文件包含字符串或其他内容,则程序不应崩溃,而是关闭文件然后停止脚本import numpy as npdef main():    # Converts into a numpy array.    # loadtxt function has the default dtype as float    x = np.loadtxt("wind.txt")    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()main()
查看完整描述

1 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

loadtxt是一个相当长的函数,但关于它的文件处理:


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()

总之,如果你给它一个文件名(一个字符串),它会打开它并注意到它owns是文件。实际的文件读取和解析dtype受try/finally子句保护。如果它拥有该文件,则将其关闭。


因此,如果ValueError由于无法转换为浮点数的字符串而得到 a,则不必担心关闭文件。事实上,即使你想,你也做不到,因为你无权使用fh手柄。


如果您希望您的代码在此值错误后执行不同的操作,请将其包装:


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()


查看完整回答
反对 回复 2022-07-12
  • 1 回答
  • 0 关注
  • 193 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号