Python 文件操作函數


Read()函數

函數說明

Read from stream.

函數語法

read(size=-1, /),返回值為str

示例:

f.read()      #全部讀取
f.read(100) #讀取100個字符

Readline()函數

函數說明

Read from stream until newline or EOF.

函數語法

readline(size=-1, /),返回值為str

示例:

f.readline()      #讀取一行數據

 Write()函數

函數說明

Write string to stream.

函數語法

write(text, /)

參數說明

參數text值需為str,返回值為int

示例:

f.write("hello world")      #將字符串寫入文件,返回的是寫入的字符長度。

 

Seek()函數

函數說明

Change the stream position to the given byte offset.The offset is interpreted relative to the position indicated by whence.

函數語法

seek(offset, whence=0, /)

參數說明

  • offset代表移動的字節偏移量
  • whence代表移動的起始位置,缺省為0

    * 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

注:當未使用二進制格式打開文件時,從當前位置或文件尾進行偏移會報“io.UnsupportedOperation: can't do nonzero cur-relative seeks”錯誤,把文件打開方式加上“b”即可。

示例:

f.seek(4,0)   #從開頭位置向后偏移4字節
f.seek(3,1)   #從當前位置向后偏移3字節
f.seek(-3,2)  #從結尾位置向前偏移3字節

 

Tell()函數

函數說明

Return current stream position.

函數語法

tell(),返回值為int

示例:

f.tell()  #返回文件當前位置,例178

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM