python對檔案的幾大基本操作

2021-06-26 20:03:13 字數 2538 閱讀 6347

讀檔案涉及的函式

每乙個檔案都有乙個指標printer, 用於記錄讀寫的位置。不管是讀,還是寫,都會從指標的位置開始。

乙個字母或數字就是乙個位元組,指標位置+1,回車\n 算兩個位元組,指標位置+2

seek()用於挪動檔案的指標,格式: seek(offset, where)  有三個模式

where=0時, 從起始位置向後移動offset個位元組

where=1時  從當前位置向後移動offset個位元組

where=2時  從文章結尾位置向後移動(即打空格)offset個位元組

其他情況:

where有時會被省略,只有offset值,比如seek(0), seek(5),這時表示seek(0,0) , seek(5,0)。即where的default值為0,從開始位置讀起。

seek(), 無返回值,即null

用法:

f = open('d:/hello.txt') #唯讀方式開啟乙個叫hello.txt的檔案

f.seek(5,0) #將檔案指標挪到第五個位元組上

tell()用於了解當前檔案指標的位置

用法:

f.tell()
read() ,readline()和readlines()函式,用於讀檔案

read()會讀文件的所有內容,並且檔案指標pointer返回到文章末尾

readline(n),從tell()+1位置開始,讀入n行檔案內容,指標挪到行尾,若n為空時,readline()預設唯讀當前行內容

readlines(),讀入所有行內容,並且檔案指標pointer返回到文章末尾

注意,read()和readlines()雖然都是讀所有檔案,但讀出來的格式不同。例如:

用read()讀出來的長這樣:

用readlines()讀出來的長這樣:

truncate()函式用於截斷。truncate(n)是指從首行首字母開始讀,到後面n個位元組截斷。執行後,n後面的所有字元被刪除。n為null的時候,即truncate()表示從當前位置(檔案指標位置)起截斷,後面字元都刪除。truncate()並不會移動指標位置。

所以truncate()一般用於擦除檔案,比如:

f = open ('hello.txt', 『w』)

print f.tell() ##位置應該是0

f.truncate() ##從第乙個位置開始截斷,後面全部擦除。即清空檔案。

總結:

對於乙個檔案的操作,大概有幾步:

1. 開啟檔案  

f = open("hello.txt", 'w')

2. 找到指標位置

f.tell()

3. 改變指標位置

f.seek()

4.讀檔案

f.read(), f.readlines(), f.readline()

5.寫檔案

f.write()

6. 截斷檔案

f.truncate()

7.關閉儲存檔案,釋放空間

f.close()

會讓指標位置移動的函式 seek(), write(), read(), readlines(), readline()

arguments的意思是 the data you pass into the methods' parameters

讀寫拷貝檔案

from sys import argv

###for copying a file from one to another

script, from_file, to_file = argv

indata = open(from_file).read()

outdata = open(to_file,'w').write(indata)

###once the copy run in one line, python will close the file automatically. you don't need to do close()

open函式開啟文件, indata表示讀出的內容

'w'表示write模式,完全清空舊有資訊重寫文件 

.write(indata)表示寫資訊indata

如果合在一行寫並沒有拆開,則不用close文件。拆開的意思是指:

first_file = open(from_file)

indata = first_file.read()

second_file = open(to_file, 'w')

outdata = second_file.write(indata)

first_file.close()

second_file.close()

python對檔案的基本操作

python中對檔案 資料夾的操作需要涉及到os模組和shutil模組。建立檔案 1 os.mknod test.txt 建立空檔案 2 open test.txt w 直接開啟乙個檔案,如果檔案不存在則建立檔案 建立目錄 os.mkdir file 建立目錄 建立多層新目錄 建立多層目錄 def ...

python對檔案的 python對檔案的讀寫

檔案 file 什麼是檔案 檔案是用於資料儲存和單位 檔案通常用來長期儲存資料 檔案中的資料是以位元組為單位進行順序儲存的 檔案的操作流程 1.開啟檔案 2.讀 寫檔案 3.關閉檔案 注 任何的作業系統,乙個應用程式同時開啟檔案的數量有最大數限制 檔案的開啟函式 open file,mode rt ...

NSFileHandle對檔案進行讀寫操作

nslog 路徑 fullpath nsfilehandle filehandle nsfilehandle filehandleforwritingatpath fullpath filehandle seektoendoffile filehandle writedata log datausi...