文件操作(十二)——open,read,close,write,seek,truncate

open函数

#!/usr/bin/env python
#-*- coding:utf8 -*-

f = open('xxx','r',encoding='utf-8')
data = f.read()
print(data)
f.close()

# readlines() 读多行,以列表的形式返回
f = open('xxx','r',encoding='utf-8')
data = f.readlines()    # ['111111\n', '2222\n', '33333\n', '44444\n', '555555']
print(data)
f.close()
des = open('xxx_new', 'w', encoding='utf-8')
des.write(data[0]) # 新文件的内容为  : 111111
des.close()
# writelines 传入一个列表
des = open('xxx_new', 'w', encoding='utf-8')
des.writelines(data)
des.close()
# 追加模式‘a'

f = open('xxx','a+',encoding='utf-8')
f.write('666666\n')
data = f.readlines()
print(data)
f.close()

# readline() 读一行
f = open('xxx','r',encoding='utf-8')
data = f.readline()
print(data)
f.close()

'''
引用另外一个文件的函数
'''
import test_import
test_import.test()

 

文件模式:

rb模式,wb模式

 

f = open('xxx','rb') # b 模式不能指定编码
data = f.read()
print(data)
f.close()
'''
hello
2222
33333
你好世界
b'hello\r\n2222\r\n33333\r\n\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\x96\xe7\x95\x8c'
'''
f = open('xxx','rb') # b 模式不能指定编码
data = f.read() # 都出来的内容就是二进制的
print(data.decode('utf-8'))     # 把读出来的二进制解码,将显示为正常的字符串
f.close()
'''
hello
2222
33333
你好世界
'''

f = open('test_1','wb') # b 模式不能指定编码
str1 = '1111\n'
str2 = '2222\n'
str11 = bytes(str1,encoding='utf-8')
f.write(str11)
f.write(str2.encode('utf-8'))
f.close()

 

tell(),seeek(),truncate()

 

# 除了read() 是以字符为单位读取,其他的是以字节为单位读取

f = open('test_1','r',encoding='utf_8',newline='') # newline 还原真的换行符,windows:\r\n,linux:\n
data = f.readline()
print(data.rstrip('\n'))    #截掉字符串的空格或指定字符(\t,\n也可以)。
print(f.tell()) #   文件光标的位置
f.seek(0)   # 移动光标的位置
print(f.tell())

data = f.readlines()
print(data)
f.close()

f = open('test_1','r+',encoding='utf_8')
f.truncate(5)   # 截断,必须要有写的权限, 保存截断参数之前的内容
f.close()

 

seek(), 有三种模式,whence对应取:0,1,2

0:表示从文件开头位置,也是默认模式

1:相对位置,相对位置要以‘b‘形式打开文件

2:倒着seek

def seek(self, offset: int, whence: int = 0) -> int:
f = open('test_1','rb')
print(f.tell()) # 0
data = f.readlines()
print(f.tell()) # 31
f.seek(-5,2) # 2 从结尾读取5个字节
print(f.tell()) # 26
data = f.read()
print(data)


利用seek读取文件最后一行的内容

f = open('test_1','rb')
for i in f:
    pos = -2
    while True:
        f.seek(pos, 2)  # 每次从文件末尾偏移pos个字节开始读
        data = f.readlines()
        if len(data) > 1:
            print("文件的最后一行是 %s" %(data[-1]).decode('utf-8'))
            break
        pos *= 2

 

转载于:https://www.cnblogs.com/xiangtingshen/p/10402744.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值