本文講述了Python文件操作類的操作實(shí)例,詳細(xì)代碼如下:
#!/usr/bin/env python#!/usr/bin/env python #coding:utf-8 # Purpose: 文件操作類#聲明一個(gè)字符串文本 poem=''' Programming is fun測試 When the work is done if you wanna make your work also fun: use Python! ''' #創(chuàng)建一個(gè)file類的實(shí)例,模式可以為:只讀模式('r')、寫模式('w')、追加模式('a') f=file('poem.txt','a') #open for 'w'riting f.write(poem) #寫入文本到文件 write text to file f.close() #關(guān)閉文件 close the file#默認(rèn)是只讀模式 f=file('poem.txt') # if no mode is specified,'r'ead mode is assumed by default while True: line=f.readline() #讀取文件的每一個(gè)行 if len(line)==0: # Zero length indicates EOF break print line, #輸出該行 #注意,因?yàn)閺奈募x到的內(nèi)容已經(jīng)以換行符結(jié)尾,所以我們在輸出的語句上使用逗號來消除自動換行。 #Notice comma to avoid automatic newline added by Python f.close() #close the file#幫助 help(file)
新聞熱點(diǎn)
疑難解答
圖片精選