谈谈python文件管理中的file、seek、truncate
来源:互联网 发布:vsftpd 指定端口 编辑:程序博客网 时间:2024/04/28 00:43
一、先介绍下file、seek、truncate的基本用法:
seek(offset,where): where=0从起始位置移动,1从当前位置移动,2从结束位置移动。当有换行时,会被换行截断。seek()无返回值,故值为None。
tell(): 文件的当前位置,即tell是获得文件指针位置,受seek、readline、read、readlines影响,不受truncate影响
truncate(n): 从文件的首行首字符开始截断,截断文件为n个字符;无n表示从当前位置起截断;截断之后n后面的所有字符被删除。其中win下的换行代表2个字符大小。
readline(n):读入若干行,n表示读入的最长字节数。其中读取的开始位置为tell()+1。当n为空时,默认只读当前行的内容
readlines读入所有行内容
read读入所有行内容
二、以下以1个例子说明以上各个函数的作用
fso = open("f:\\a.txt",'w+') '以w+方式,并非a方式打开文件,故文件原内容被清空
print fso.tell() '文件原内容被清空,故此时tell()=0
fso.write("abcde\n") '写入文件abcde\n,因为换行\n占两个字符,故共写入7个字符
print fso.tell() '此时tell()=7
fso.write("fghwm") '又写入文件fghwm,故此时文件共写入7+5 =142个字符
print fso.tell() '此时tell()=12
fso.seek(1, 0) '从起始位置即文件首行首字符开始移动1个字符
print fso.tell() ‘此时tell() =1
print fso.readline() '读取当前行,即文件的第1行,但是从第二个字符(tell()+1)开始读,结果为:bcde。
'若换成for读取整个文件或read读取整个文件则结为bcdefghwm
print fso.tell() ‘因为readline此时tell() =7,
fso.truncate(8) '从写入后文件的首行首字符开始阶段,截断为8个字符,即abcde\nf,即文件的内容为:abcde\nf
print fso.tell() ‘tell() 依旧为7,并为受truncate(8)影响,但是此时文件内容为abcde\nf
print fso.readline() ‘从tell()+1=8开始读取,读取当前行内容:f
fso.close()
- 谈谈python文件管理中的file、seek、truncate
- 谈谈python文件管理中的file、seek、truncate
- python文件管理中的file、seek、truncate
- python文件管理中的file、seek、truncate
- python 文件操作中的 file、seek、truncate 用法
- python 文件操作中的 file、seek、truncate 用法
- python的文件操作file:(内置函数,如seek、truncate函数)
- python基础-打开模式、seek、修改文件、with上下文管理、truncate
- Python file.seek()文件游标移动操作方法
- Python file.truncate()方法
- [Android] File 文件定位 seek
- Python中的文件管理
- python中 file.seek( )和file.readline() 的用法
- truncate file
- python之文件读取seek(),tell()函数
- Python入门:中file.seek函数的用法
- python seek()
- python seek()
- Android 4.0操作系统21项新特性
- 批处理bat简单教程
- 老单增加工具栏按钮。。详细方法
- android input system(frameworks) analysis -- InputManager (1)
- 产品经理的权力之争
- 谈谈python文件管理中的file、seek、truncate
- Android MediaPlayer基本使用方式
- SingleTon单例模式请不要滥用
- .Net 操作文本文件
- Ruby on Rails的神奇
- 揭开正则表达式的神秘面纱
- Hadoop启动时出现Unrecognized option: -jvm的问题(收集)
- 用InternetCheckConnection 判断是否接通外网
- 【三】离散化动态规划