Head First Python第3砸紊、4章學(xué)習(xí)筆記

sketch.txt
Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
Other Man: Now let's get one thing quite clear: I most definitely told you! #一行多個(gè):
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause) #沒有:
Other Man: Yes it is!
Man: No it isn't!
(pause)
Man: It's just contradiction!
Other Man: No it isn't!
Man: It IS!
Other Man: It is NOT!
Man: You just contradicted me!
Other Man: No I didn't!
Man: You DID!
Other Man: No no no!
Man: You did just then!
Other Man: Nonsense!
Man: (exasperated) Oh, this is futile!!
(pause)
Other Man: No it isn't!
Man: Yes it is!


***=opne()
***.close()
os.chdir()切換目錄
os.getcwd()查看當(dāng)前目錄
readline()獲取一行數(shù)據(jù)
seek()回到文件起始位置
split("*")以某個(gè)符號(hào)為分隔符,默認(rèn)盡可能多的分割
split("",1)分割一次
無法更改的常量列表叫元組
數(shù)據(jù)不符合期望格式ValueError
數(shù)據(jù)無法正常訪問IOError
方法一:考慮每種異常
import os
if os.path.exists('sketch.txt'):    
    data = open('sketch.txt')
    for each_line in data:
        if not each_line.find(':') == -1:
            (role, line_spoken) = each_line.split(':',1)
            print(role),
            print('said:'),
            print(line_spoken),
    data.close()
else:
    print("The file is missing!")
方法二:增加異常處理
try:
    data = open('sketch.txt')
    for each_line in data:
        try:
            (role, line_spoken) = each_line.split(':')
            print(role),
            print('said:'),
            print(line_spoken),
        except:
            pass
    data.close()
except:
    print("The file is missing!")
推薦使用異常處理,但是需要指定異常而不是所有異常統(tǒng)一處理

為代碼增加輸出
print("",file=*)
open("*.out","w")#追加a,寫和讀w+
讀寫都需要close()

輸出到屏幕
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() #刪除空白
            if role == 'Man':
                man.append(line_spoken)
            elif role == 'Other Man':
                other.append(line_spoken)
        except ValueError:
            pass
    data.close()
except IOError:
    print("The file is missing!")
print(man)
print(other)

輸出到文件
man = []
other = []

try:
    data = open('sketch.txt',encoding='utf8')
    for each_line in data:
        try:
            (role, line_spoken) = each_line.split(':',1)
            line_spoken = line_spoken.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 file is missing!")
    
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)
    #man_file.close()modify:把close移到finally厢呵,保證關(guān)閉
    #other_file.close()   
except IOError:
    print('File error.')
finally:
    if 'man_file' in locals(): #增加文件不存在的判斷
        man_file.close()
    if 'other_file' in locals():
        other_file.close()

優(yōu)化close&&日志版
man = []
other = []

try:
    with open('sketch.txt',encoding='utf8') as data: #使用with替代finally
        for each_line in data:
            try:
                (role, line_spoken) = each_line.split(':',1)
                line_spoken = line_spoken.strip()
                if role == 'Man':
                    man.append(line_spoken)
                elif role == 'Other Man':
                    other.append(line_spoken)
            except ValueError:
                pass  
except IOError as Ierr:
    print("error:"+str(Ierr))
    
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 err: #輸出具體錯(cuò)誤
    print('File error:'+str(err)) #BIF要求異常對(duì)象為字符串

修改print_lol函數(shù)使輸出的文件滿足一定格式

將輸出的文件持久儲(chǔ)存

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市科阎,隨后出現(xiàn)的幾起案子述吸,更是在濱河造成了極大的恐慌,老刑警劉巖锣笨,帶你破解...
    沈念sama閱讀 218,451評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蝌矛,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡错英,警方通過查閱死者的電腦和手機(jī)入撒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來椭岩,“玉大人茅逮,你說我怎么就攤上這事∨懈纾” “怎么了献雅?”我有些...
    開封第一講書人閱讀 164,782評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長塌计。 經(jīng)常有香客問我挺身,道長,這世上最難降的妖魔是什么锌仅? 我笑而不...
    開封第一講書人閱讀 58,709評(píng)論 1 294
  • 正文 為了忘掉前任章钾,我火速辦了婚禮墙贱,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘贱傀。我一直安慰自己惨撇,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評(píng)論 6 392
  • 文/花漫 我一把揭開白布府寒。 她就那樣靜靜地躺著魁衙,像睡著了一般。 火紅的嫁衣襯著肌膚如雪椰棘。 梳的紋絲不亂的頭發(fā)上纺棺,一...
    開封第一講書人閱讀 51,578評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音邪狞,去河邊找鬼。 笑死茅撞,一個(gè)胖子當(dāng)著我的面吹牛帆卓,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播米丘,決...
    沈念sama閱讀 40,320評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼剑令,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了拄查?” 一聲冷哼從身側(cè)響起吁津,我...
    開封第一講書人閱讀 39,241評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎堕扶,沒想到半個(gè)月后碍脏,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,686評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡稍算,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評(píng)論 3 336
  • 正文 我和宋清朗相戀三年典尾,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片糊探。...
    茶點(diǎn)故事閱讀 39,992評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡钾埂,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出科平,到底是詐尸還是另有隱情褥紫,我是刑警寧澤,帶...
    沈念sama閱讀 35,715評(píng)論 5 346
  • 正文 年R本政府宣布瞪慧,位于F島的核電站髓考,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏汞贸。R本人自食惡果不足惜绳军,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評(píng)論 3 330
  • 文/蒙蒙 一印机、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧门驾,春花似錦射赛、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至聂沙,卻和暖如春秆麸,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背及汉。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評(píng)論 1 270
  • 我被黑心中介騙來泰國打工沮趣, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人坷随。 一個(gè)月前我還...
    沈念sama閱讀 48,173評(píng)論 3 370
  • 正文 我出身青樓房铭,卻偏偏與公主長得像,于是被迫代替她去往敵國和親温眉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子缸匪,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容