Python文件操作類操作實(shí)例代碼

字號:


    #!/usr/bin/env python
    01 #!/usr/bin/env python
    02 #coding:utf-8
    03 # Author: 酷酷
    04 # Purpose: 文件操作類
    05 # Created: 2011/1/1
    06
    07 #聲明一個(gè)字符串文本
    08 poem='''
    09 Programming is fun測試
    10 When the work is done
    11 if you wanna make your work also fun:
    12 use Python!
    13 '''
    14 #創(chuàng)建一個(gè)file類的實(shí)例,模式可以為:只讀模式('r')、寫模式('w')、追加模式('a')
    15 f=file('poem.txt','a') #open for 'w'riting
    16 f.write(poem) #寫入文本到文件 write text to file
    17 f.close() #關(guān)閉文件 close the file
    18
    19 #默認(rèn)是只讀模式
    20 f=file('poem.txt')
    21 # if no mode is specified,'r'ead mode is assumed by default
    22 while True:
    23 line=f.readline() #讀取文件的每一個(gè)行
    24 if len(line)==0: # Zero length indicates EOF
    25 break
    26 print line, #輸出該行
    27 #注意,因?yàn)閺奈募x到的內(nèi)容已經(jīng)以換行符結(jié)尾,所以我們在輸出的語句上使用逗號來消除自動換行。
    28
    29 #Notice comma to avoid automatic newline added by Python
    30 f.close() #close the file
    31
    32 #幫助
    33 help(file)