Python第4課-深いファイルと異常(データの持続化)


Python第三課——初探ファイルと異常は主にファイルからデータを読み出し、異常処理の基本構文を学習する
このレッスンでは、Pythonを使用してテキストファイルにデータを書き込む方法、異常処理の詳細を学習します.
1、ファイルを作成し、必要なデータをファイルに書き込む.

'''   demo      (conversations)   (role)   ,           '''

man = [] #      list       role conversations
other = []

try:
    data = open('sketch.txt')
    try:
        for each_line in data:
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            if role == 'man': #    role       list
                man.append(line_spoken)
            else:
                other.append(line_spoken)
    except ValueError:
        pass
    data.close() #                 
except IOError:
    print('The file is missing!')

try:
    man_file = open('man_data.txt', 'w') #                 ,           ,open()       
    other_file = open('other_data.txt', 'w') # 'w'        ' '  

    print(man, file = man_file) #print()    file         
    print(other, file = other_file)

    man_file.close() #                 
    other_file.close()
except IOError:
    print('File Error!')

2、上記のコードの異常処理ロジックとコードを改善する:
上のコードの異常処理方式は依然として不完全で、考えてみれば、man_file.close()文の前にコードにエラーが発生した場合、データファイルオブジェクトは閉じられません.
改善コード:

man = [] 
other = []

try:
    data = open('sketch.txt')
    try:
        for each_line in data:
            (role, line_spoken) = each_line.split(':', 1)
            line_spoken = line_spoken.strip()
            if role == 'man':
                man.append(line_spoken)
            else:
                other.append(line_spoken)
    except ValueError:
        pass
    data.close()
except IOError as ioerr: # IOError      ioerr  
    print('File Error :' + str(ioerr)) # ioerr        

try:
    man_file = open('man_data.txt', 'w')
    other_file = open('other_data.txt', 'w')

    print(man, file = man_file)
    print(other, file = other_file)
except IOError as ioerr:
    print('File Error: ' + str(ioerr))
finally: #  try     except            ,finally       
    if 'man_file' in locals(): #            ,loclas() BIF             
        man_file.close()
    if 'man_file' in locals():
        man_file.close()

3、Pythonのファイル処理の文法糖:
with文を使用すると、ファイル処理のコードを簡略化でき、ファイルを閉じることを考慮する必要がなく、ファイル異常処理文のfinally文を切り取ることができます.
役割1:文法を簡略化し、作業量を減らす.
作用2:論理抽象を通じて、私たちの脳細胞の死亡速度と間違い確率を減らす.
上記のコードの第2セグメントの改善:

try:
    with open('man_data.txt', 'w') as man_file:
        print(man, file = man_file)
    with open('other_data.txt', 'w') as other_file:
        print(other, file = other_file)
except IOError as ioerr:
    print('File Error: ' + str(ioerr))

OR

try:
    with open('man_data.txt', 'w') as man_file, open('other_data.txt', 'w') as other_file:
        print(man, file = man_file)
        print(other, file = other_file)
except IOError as ioerr:
    print('File Error: ' + str(ioerr))