Python基礎 十六 檔案讀寫

2021-09-11 15:34:07 字數 1177 閱讀 3853

1、seek(位元組, [0, 1, 2])

change stream position.

change the stream position to the given byte offset. the offset is

interpreted relative to the position indicated by whence. values

forwhence are:

* 0 -- start of stream (the default); offset should be zero or positive

* 1 -- current stream position; offset may be negative

* 2 -- end of stream; offset is usually negative

return the new absolute position.

複製**

改變流的位置

根據位元組數改變流的偏移量, 偏移量相對於何處開始偏移, 下面是對應的值:

0: 流開始的位置(預設), 從零開始偏移

1: 當前的位置, 位元組可以是負數

2: 流結尾的位置, 位元組通常是負數

返回乙個新的絕對位置

複製**

2、示例

3、tell()方法

1、read(位元組數)

2、readline([limit])

我們現在test檔案中加入第二行資料:abcdefg

3、readlines()

4、for in

5、readable(): 判定檔案是否可讀

注意:

一般檔案特別大的時候, 可以使用readline方法, 按行載入, 可節省記憶體, 但是相比於其他兩個讀取方法, 效能較低

read(位元組數)和readlines方法, 一次性讀取檔案所有內容, 占用記憶體較多, 但是效能比較高

1、write("內容")

2. writable(): 判定檔案是否支援寫入操作

close(): 關閉檔案, 釋放系統資源, 同時將緩衝區內容一次性寫入到磁碟中

flush()

python基礎 檔案讀寫

1.讀寫方式 f open text r encoding utf 8 2.寫讀方式 f open text w encoding utf 8 3.追加方式 f open text a encoding utf 8 4.讀方式 f open text r encoding utf 8 5.寫方式 f...

python基礎 讀寫檔案

import os print os.getcwd import os os.chdir 你想要的路徑 import os os.makedirs 你想要的檔案目錄 import os print os.path.abspath demo import os print os.path.isabs ...

python檔案讀寫(基礎)

1.開啟檔案 讀寫檔案是常見的io操作,python內建了讀寫檔案的函式,方便了檔案的io操作。檔案讀寫之前需要開啟檔案,確定檔案的讀寫模式。open函式用來開啟檔案,語法如下 open name,mode,buffering open函式使用乙個檔名作為唯一的強制引數,然後返回乙個檔案物件。模式 ...