python对文件的几大基本操作

来源:互联网 发布:javascript 廖雪峰 编辑:程序博客网 时间:2024/06/04 23:25

读文件涉及的函数

每一个文件都有一个指针printer, 用于记录读写的位置。不管是读,还是写,都会从指针的位置开始。

一个字母或数字就是一个字节,指针位置+1,回车\n 算两个字节,指针位置+2


seek()用于挪动文件的指针,格式: seek(offset, where)  有三个模式

      where=0时, 从起始位置向后移动offset个字节

      where=1时  从当前位置向后移动offset个字节

      where=2时  从文章结尾位置向后移动(即打空格)offset个字节

其他情况:

      where有时会被省略,只有offset值,比如seek(0), seek(5),这时表示seek(0,0) , seek(5,0)。即where的default值为0,从开始位置读起。

      seek(), 无返回值,即null

用法:

      

f = open('d:/hello.txt') #只读方式打开一个叫hello.txt的文件f.seek(5,0) #将文件指针挪到第五个字节上

      

tell()用于了解当前文件指针的位置

用法:

f.tell()

read() ,readline()和readlines()函数,用于读文件

read()会读文档的所有内容,并且文件指针pointer返回到文章末尾

readline(n),从tell()+1位置开始,读入n行文件内容,指针挪到行尾,若n为空时,readline()默认只读当前行内容

readlines(),读入所有行内容,并且文件指针pointer返回到文章末尾


注意,read()和readlines()虽然都是读所有文件,但读出来的格式不同。例如:

一个文本文件长这样:


用read()读出来的长这样:


用readlines()读出来的长这样:


truncate()函数用于截断。truncate(n)是指从首行首字母开始读,到后面n个字节截断。执行后,n后面的所有字符被删除。n为null的时候,即truncate()表示从当前位置(文件指针位置)起截断,后面字符都删除。truncate()并不会移动指针位置。

所以truncate()一般用于擦除文件,比如:

f = open ('hello.txt', ‘w’)print f.tell()  ##位置应该是0f.truncate()  ##从第一个位置开始截断,后面全部擦除。即清空文件。

总结:

对于一个文件的操作,大概有几步:

1. 打开文件  

f = open("hello.txt", 'w')

2. 找到指针位置

f.tell()

3. 改变指针位置

f.seek()

4.读文件

f.read(), f.readlines(), f.readline()

5.写文件

f.write()

6. 截断文件

f.truncate()

7.关闭保存文件,释放空间

f.close()


会让指针位置移动的函数 seek(), write(), read(), readlines(), readline()

--------------------------------------------------------

arguments的意思是 the data you pass into the methods' parameters


读写拷贝文件

from sys import argv###for copying a file from one to anotherscript, from_file, to_file = argvindata = open(from_file).read()outdata = open(to_file,'w').write(indata)###once the copy run in one line, python will close the file automatically. you don't need to do close()

open函数打开文档, indata表示读出的内容

'w'表示write模式,完全清空旧有信息重写文档 

.write(indata)表示写信息indata

如果合在一行写并没有拆开,则不用close文档。拆开的意思是指:

first_file = open(from_file)indata = first_file.read()second_file = open(to_file, 'w')outdata = second_file.write(indata)first_file.close()second_file.close()



0 0