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

 

posted @ 2018-10-29 10:33  wolfking429  阅读(2194)  评论(0)    收藏  举报