设为首页 加入收藏

TOP

python学习-37 其他的文件处理方法
2019-07-11 22:10:12 】 浏览:33
Tags:python 学习 -37 其他 文件 处理 方法
f = open('test.txt','r+',encoding='utf-8')

f.flush()        # 刷新

f.readline()
print(f.tell())     # 说明光标位置在哪里 (\r\n 也算两个字节)
print('-------------------------------')

f.seek(3)                      # 在文件test.txt里第一行abc123,  3的位置
print(f.tell())
print(f.read())

f.truncate(10)                # 截取

运行结果:

7
-------------------------------
3
13
123

Process finished with exit code 0

 

 

seek 方法的补充

 

1.光标的移动

f = open('test.txt','rb')              # 以2进制的方式
print('目前光标的位置:',f.tell())
print('--------------------')

f.seek(10)
print(f.tell())
print('-------------')

f.seek(3)                               # 默认从文件开始计算光标位置
print(f.tell())
print(f.read())
print('-------------')

f.seek(10,1)                        #  相对路径,从上一步的光标位置开始计算10字节
print(f.tell())
print('--------------')

f.seek(-10,2)                # 从文件末尾位置开始计算10字节
print(f.tell())              # 光标在从前往后数的第40字节的位置
print(f.read())               # 读取现在光标的位置
print('-----------')

运行结果:

目前光标的位置: 0
--------------------
10
-------------
3
b'13\r\n123\r\n\xe4\xbd\xa0\xe5\xa5\xbd\r\nhello,word\r\nqwertyuiop46579813'
-------------
60
--------------
40
b'op46579813'
-----------

Process finished with exit code 0

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇python基础知识三 字典-dict + 菜.. 下一篇第三章 数据类型之整型、布尔、字..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目