【Python】文件操作

1 只读(模式为r,rb)

# 1. 文件在硬盘上时,一定是:utf-8,gbk......即已经编码好
# 2. rb, bytes,                  rb
# 3. r,  转换encoding=utf-8      r   encoding:utf-8

# 读文件
# obj = open('D:\\xxxx1.txt',encoding='utf-8',mode='r')
# content = obj.read() # 字符串类型,文件编码在硬盘上为utf-8要在转为内存中的Unicode,python中字符串在内存中默认为Unicode编码
# obj.close()
# print(content,type(content))

# obj = open('D:\xxxxx1.txt',mode='rb')
# content = obj.read() # bytes类型
# obj.close()
# print(content,type(content))

2 只写(会覆盖之前文件中的内容,模式为w,wb)

# obj = open('美女.txt',mode='w',encoding='utf-8')
# obj.write("海角-贾敏")
# obj.close()

# obj = open('美女.txt',mode='wb')
# obj.write("海角-贾敏22222".encode('utf-8'))
# obj.close()

3 只追加(在文件末尾写新的东西,不能读,模式为a,ab)

# obj = open('美女.txt',mode='a',encoding='utf-8')
# obj.write("小红")
# obj.close()

# obj = open('美女.txt',mode='ab')
# data = obj.read()         #报错
# obj.close()

4 又读又写(最常用,模式r+)

# obj = open('美女.txt',mode='r+',encoding='utf-8')
# data = obj.read(1) # 读
# # 情况一:
# # obj.write('6') # 在最后继续写
# # 情况二:
# # obj.seek(1)
# # obj.write('6') # 定位到指定位置
# obj.close()
# print(data)

5 seek() 指定指针的位置,代表字节位置

seek(1)   在第一个字节之后,代表字节

6 tell() 读取当前指针的位置

num=int(input("要读取的字符个数"))
data=obj.read(num)         # read方法会改变指针位置
imp=input(''从当前位置开始向后覆盖内容'')
obj.seek(obj.tell())

7 其他方法

# 是否可写
# obj.writable()
# 是否可读
# obj.readable()
# 将内存中内容刷到硬盘
# obj.flush()
# obj.tell()
# data = obj.readline()
# print(data)
# data = obj.readline()              #调用一次只读文件中的一行
# print(data)
# 截取文件内容,根据指针位置,只保留指针之前数据
# obj.truncate()

for line in obj:              #一行一行读取文件里面的内容
    print(line)
obj.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bug 挖掘机

支持洋子

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值