13.文件:因为懂你,所以永恒
生活随笔
收集整理的這篇文章主要介紹了
13.文件:因为懂你,所以永恒
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
什么是文件?
.exe .avi .mp4 .jpg .ppt
打開文件,并返回文件對象:open
open('文件名',打開方式) >>> f = open('G:\\FishC.txt') >>> f <open file 'G:\\FishC.txt', mode 'r' at 0x0000000002D32E40> >>> f = open('G:\\FishC.txt','a') >>> f <open file 'G:\\FishC.txt', mode 'a' at 0x0000000002D32ED0>http://bbs.fishc.com/forum.php?mod=viewthread&tid=45279&extra=page%3D1%26filter%3Dtypeid%26typeid%3D403
read()
seek:移動文件指針
tell:獲得文件指針的當前位置
打印文件的方法:
方法1: >>> f = open('G:\\FishC.txt','r') >>> lines = list(f) #把文件中的內容轉換成list >>> lines ['I \n', 'love\n', 'Fish.com'] >>> for each_line in lines: #定義一個變量依次獲取lines列表中的每一個字符串print each_line #并打印I loveFish.com 【說明】這種效率很低方法2:官方推薦 >>> f = open('G:\\FishC.txt','r') >>> for each_line in f:print each_lineI loveFish.com寫入文件:如果要寫入文件,必須用w或a的方式打開文件
>>> f = open('G:\\FishC.txt','a') >>> f.write('I love FishC') >>> f.close() #操作完成后,記住一定要關閉文件 >>> >>> f = open('G:\\FishC.txt','r') >>> f.read() 'I \nlove\nFish.comI love FishC'—-
—-
習題
文件中的內容: A:"You love Fish?" B:"Yes." ====================== A:"I love Fish?" B:"No." ====================== A:"We love Fish?" B:"Yes or No." ======================習題要求: 將A的對話單獨保存為A_*.txt(去掉A:) 將B的對話單獨保存為B_*.txt(去掉B:)文件中總共有三段話,分別保存為A_1.txt,A_2.txt,A_3.txt,B_1.txt,B_2.txt,B_3.txt共6個 文件(提示:文件中不同的對話之間已經用==========分隔開)print('Begin\n')f = open('G:\\FishC.txt','r')#定義a,b列表進行分別保存A,B的對話 a = [] b = [] count = 0for each_line in f: #依次讀取文件中的內容if each_line[:3] != '===': #判斷是否等于‘===’,如果不等于,就要進行保存(name,spoken) = each_line.split(':',1)if(name == 'A'):a.append(spoken)elif(name == 'B'):b.append(spoken)else:#把a,b中的內容寫入新的文件中count = count + 1file_A = 'G:\\A_'+str(count)+'.txt'file_B = 'G:\\B_'+str(count)+'.txt'f_A = open(file_A,'w')f_A = open(file_A,'w')for A_line in a:f_A.write(A_line)for B_line in b:f_B.write(B_line)file_A.clear()file_B.clear()f_A.close()f_B.close() f.close() print('End\n')總結
以上是生活随笔為你收集整理的13.文件:因为懂你,所以永恒的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 12.集合:在我的世界里,你就是唯一 /
- 下一篇: 14.文件系统:高大上的东西——impo