python文件读写操作

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()




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值