headfirstpython(第4章)-学習ノート

3443 ワード

実は永続ストレージにはファイルだけでなく、データベースなども含まれています.本章では、まず一部を紹介し、よく知っておきます.
pythonデータに詳しい
#!/usr/bin/python
# -*- coding: utf-8 -*-


man = []
other = []

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

print (man)
print (other)

print(「Norwegian Blues XXXX」、file=out)はpython 3.0の使い方ですが、旧バージョンのpythonが
data.write(result)

ファイルを書き込む場合は、ファイルを開くときはw書き込みモードで、読み込むとrです.
try:exceptで処理できない場合はfinallyを使用します
finallyはtry:exceptのエラーにかかわらず、総会を代表して実行されます.
#!/usr/bin/python
# -*- coding: utf-8 -*-

man = []
other = []

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

finally:
    data.close()

取得したエラー情報の詳細印刷
#!/usr/bin/python
# -*- coding: utf-8 -*-


man = []
other = []

try:
    data = open('sketch.txt')
    for each_line in data:
            try:
                    (role,line_spoken) = each_line.split(':',1)
                    line_spoken = line_spoken.strip()  #      :        line_spoken   ,python        ,                    strip()   ,               
                    if role == 'Man':
                            man.append(line_spoken)
                    elif role == 'Other Man':
                            other.append(line_spoken)
            except ValueError:
                    pass
    data.close()
except IOError as err:
    print('The datafile is missing!' + str(err)) #          ,      str   

finally:
    data.close()

例えば詳細なエラーメッセージは、File error:XXXX NO such file or directory:'sketchと表示されます.txt'
Openの代わりにwithを使う
withはオープンのように最後にcloseで閉じるのではなく、自動的にファイルを閉じるので
with open('its.txt',"w") as data:
    print data

勉強はピックで
pickleの使用原因はpython専用の永続的なストレージ方式であり、フォーマットの問題を気にせず、直接保存し、直接使用することができる点である.
dumpで保存、loadで復元
#!/usr/bin/python
# -*- coding: utf-8 -*-

import pickle
with open('mydata.pickle','w') as mysavedata:
    pickle.dump([1,2,3],mysavedata)

a = []
with open('mydata.pickle','r') as myrestoredata:
    a = pickle.load(myrestoredata)
print a

テキストリンク:http://www.godblessyuan.com/2015/04/27/head_first_python_chapter_5_learning/