亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

做一個基本的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 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號