python文件读写由io.FileIO包装,具体细节可以使用如下命令查看
dir(io.FileIO) #查看FileIO所包含的成员
help(io.FileIO) #查看FileIO的类说明以及成员说明
help(io.FileIO.member) #查看成员说明
FileIO常用的方法有
close, fileno, flush, read, readline, readlines, seek, tell, truncate, write, writelines
如下为示例
import io
file_in = open("test.txt", "r")
print("file position before read: ", file_in.tell())
content = file_in.read()
print("read all file content: ", content)
print("file position after read: ", file_in.tell())
file_in.seek(0)
content = file_in.read(10)
print("read 10 bytes from file: ", content)
file_in.seek(0)
file_out = open("out.txt", "w")
line=file_in.readline()
while line:
file_out.write(line)
line=file_in.readline()
else:
file_out.flush()
print("input file fileno : ", file_in.fileno())
print("output file fileno : ", file_out.fileno())
file_in.seek(0)
print("file position after seek to begin: ", file_in.tell())
l = file_in.readlines()
print("a list has been read from file: ", l)
file_out.writelines(l)
print("a list has been writen to file: ", l)
file_in.seek(0)
for line in file_in:
print("line : ", line, end="")
file_out.truncate(10)
file_in.close()
file_out.close()