文件操作


文件操作

hello = bytes('hello',encoding='utf-8')
print(hello)
# 二进制 python解释器 程序员

bytes 转换为 字符串有一下两种方法,str(),decode()
hello1 =str(hello,encoding='utf-8')
hello2 = hello.decode('utf-8')


r ,只读模式【默认】
w,只写模式【不可读;不存在则创建;存在则清空内容;】
x, 只写模式【不可读;不存在则创建,存在则报错】
a, 追加模式【可读; 不存在则创建;存在则只追加内容;】

# 以wb的方式打开,避免忘记关闭用with as

with open('a.txt','wb') as f:
str = '乔丹'
byt_str = bytes(str,encoding='utf-8')
f.write(byt_str)




f.tell() 读取指针位置
f.seek() 设置指针位置
f.read() 不添加参数,默认读取全部
f.readline() 读取一行数据
f.truncate() 截取指针以前的数据
f.close()
f.flush()
f.write()

r+ 从头开始读,写追加,指针移到最后
f = open('a.txt','r+',encoding='utf-8')
print(f.tell())
print(f.read(3)) # 默认是以字符方式读取,如果是rb+则是字节方式读取,一个汉字3个字节
print(f.tell())

print(f.read(3)) # 在close之前,下一次读取记住上一次读取的位置
print(f.tell())

f.seek(0)
print(f.read(3))
print(f.tell())

f.write('sb') # 写的时候最后,把指针跳到最后在写
print(f.tell())
f.close()

3.w+ 先清空,再写指针到最后,设置指针位置再读

f = open('a.txt','w+',encoding='utf-8')
print(f.read())

f.write('乔丹')
f.seek(0)
print(f.read())

f.close()

x+ 和w+相同,如果文件纯在报错

a+ 因为a为追加,所有打开的同时,指针已经到最后了,
f = open('a.txt','a+',encoding='utf-8')
print(f.tell())
f.write('sb')
f.seek(0)
print(f.read())
f.close()


f = open('a.txt','r+')
print(f.tell())
print(f.seek(20))
f.truncate()
f.close()

f = open('a.txt','r') # f 对象被循环
for i in f:
print(i,end='')

自动close,with 同时打开两个文件,
with open('a.txt','r') as f1, open('c.txt','w')as f2:
for eachline in f1:
f2.write(eachline)


转载于:https://www.cnblogs.com/lovuever/p/6639613.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值