今天的主要内容是:
- 撒
檔案操作
對檔案操作的流程:
- 打開檔案,得到檔案句柄并指派給一個變量
- 通過句柄對檔案進行操作
- 關閉檔案
現有檔案如下:
tonghuazhen
聽說白雪公主在逃跑
小紅帽在擔心大灰狼
聽說瘋帽喜歡愛麗絲
醜小鴨會變成白天鵝
聽說彼得潘總長不大
傑克他有豎琴和魔法
聽說森林裡有糖果屋
灰姑娘丢了心愛的玻璃鞋
隻有睿智的河水知道
白雪是因為貪玩跑出了城堡
小紅帽有件抑制自己
變成狼的大紅袍
總有一條蜿蜒在童話鎮裡七彩的河
沾染魔法的乖張氣息
卻又在愛裡曲折
川流不息揚起水花
又卷入一簾時光入水
讓所有很久很久以前
都走到幸福結局的時刻
View Code
打開檔案的模式有:
- r,隻讀模式(預設)。
- w,隻寫模式。【不可讀;不存在則建立;存在則删除内容;】
- a,追加模式。【可讀; 不存在則建立;存在則隻追加内容;】
"+" 表示可以同時讀寫某個檔案
- r+,可讀寫檔案。【可讀;可寫;可追加】
- w+,寫讀
- a+,同a
"U"表示在讀取時,可以将 \r \n \r\n自動轉換成 \n (與 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示處理二進制檔案(如:FTP發送上傳ISO鏡像檔案,linux可忽略,windows處理二進制檔案時需标注)
- rb
- wb
- ab
知道了以上的模式後,現在就來進入我們的操作:
- read:讀
1 f = open("yesterday","r",encoding="utf-8")#檔案句柄 [檔案名/操作首字母/字元編碼]
2 #r = read 讀
3
4 data = f.read()
5 print(data)
6 f.close()
- write:寫
1 f = open("yesterday","w",encoding="utf-8")#檔案句柄 [檔案名/操作首字母/字元編碼]
2 #w = write 寫 重新建立新文檔,如果文檔名稱有重複則覆寫原文檔
3
4 f.write("\n人心無可填\n")
5 f.write("河水太淺,怎托得起,歲月的積澱")
6 f.close()
- append:追加
1 f = open("yesterday2","a",encoding="utf-8")#檔案句柄 [檔案名/操作首字母/字元編碼]
2 #a = append 追加 隻能追加,不能讀
3
4 f.write("\n人心無可填......\n")
5 f.write("河水太淺,怎托得起,歲月的積澱........")
6 f.close()
- 讀前五行代碼:
1 f = open("yesterday","r",encoding="utf-8")#檔案句柄 [檔案名/操作首字母/字元編碼]
2
3 #讀前五行
4 print(f.readline())
5 print(f.readline())
6 print(f.readline())
7 print(f.readline())
8 print(f.readline())
- 用循環寫前五行代碼:
1 #讀前五行
2 for i in range(5):
3 print(f.readline())
- 将其變為清單格式輸出:
1 print(f.readlines())#變為清單,每一行是一個元素
輸出結果為:

這就是清單的格式
- 如果用循環輸出這個清單:
1 #循環清單
2 for line in f.readlines():
3 print(line.strip())# .strip()空格和換行都去掉
這裡用到了Python strip()方法:
描述
Python strip() 方法用于移除字元串頭尾指定的字元(預設為空格)。
文法
strip()方法文法:
str.strip([chars]);
- 列印文檔中的前十行:
1 #列印前10行 , f.readlines()隻适合讀小檔案
2 for index,line in enumerate(f.readlines()):
3 if index == 9:
4 print("這是一條分割線".center(50,"-"))
5 continue
6 print(line.strip())
但這方法隻适合列印小檔案,如果資料較大我們用下面這種方法:
1 count = 0
2 for line in f:
3 if count == 9:
4 print("---分割線---")
5 count += 1
6 continue
7 print(line)
8 count += 1
輸出結果為:
其它文法:
def close(self): # real signature unknown; restored from __doc__
"""
Close the file.
A closed file cannot be used for further I/O operations. close() may be
called more than once without error.
"""
pass
def fileno(self, *args, **kwargs): # real signature unknown
""" Return the underlying file descriptor (an integer). """
pass
def isatty(self, *args, **kwargs): # real signature unknown
""" True if the file is connected to a TTY device. """
pass
def read(self, size=-1): # known case of _io.FileIO.read
"""
注意,不一定能全讀回來
Read at most size bytes, returned as bytes.
Only makes one system call, so less data may be returned than requested.
In non-blocking mode, returns None if no data is available.
Return an empty bytes object at EOF.
"""
return ""
def readable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a read mode. """
pass
def readall(self, *args, **kwargs): # real signature unknown
"""
Read all data from the file, returned as bytes.
In non-blocking mode, returns as much as is immediately available,
or None if no data is available. Return an empty bytes object at EOF.
"""
pass
def readinto(self): # real signature unknown; restored from __doc__
""" Same as RawIOBase.readinto(). """
pass #不要用,沒人知道它是幹嘛用的
def seek(self, *args, **kwargs): # real signature unknown
"""
Move to new file position and return the file position.
Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
are SEEK_CUR or 1 (move relative to current position, positive or negative),
and SEEK_END or 2 (move relative to end of file, usually negative, although
many platforms allow seeking beyond the end of a file).
Note that not all file objects are seekable.
"""
pass
def seekable(self, *args, **kwargs): # real signature unknown
""" True if file supports random-access. """
pass
def tell(self, *args, **kwargs): # real signature unknown
"""
Current file position.
Can raise OSError for non seekable files.
"""
pass
def truncate(self, *args, **kwargs): # real signature unknown
"""
Truncate the file to at most size bytes and return the truncated size.
Size defaults to the current file position, as returned by tell().
The current file position is changed to the value of size.
"""
pass
def writable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a write mode. """
pass
def write(self, *args, **kwargs): # real signature unknown
"""
Write bytes b to file, return number written.
Only makes one system call, so not all of the data may be written.
The number of bytes actually written is returned. In non-blocking mode,
returns None if the write would block.
"""
pass
View Code
轉載于:https://www.cnblogs.com/cxylff/p/8521938.html