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