Python 基本文件操作
Python(2.7) 里面的基本的文件操作包含两个部分第一是内置的open函数,第二是文件类file. python shell下通过help(open)
可以查看到open这个函数支持的参数。
open(name[, mode[, buffering]]) -> file object
第一个参数表示文件名称,第二个参数表示文件操作的模式,具体的操作模式列表如下
一共12种模式。主要模式是r(只读) w(只写) a(追加内容)。而+和b可以看成是模式的拓展,+表示读写都可进行,b表示的纯二进制操作。有一点必须注意,即是当模式中涉及到b时,特别是针对文本文件的二进制读取需要小心。在windows下当以字符(r)写入回车符号的时候。其实存储的是两个字符,所以此时以b模式读取出的时候会出现字符串长度大于写入长度
fe = open('testb.txt','w')
ss_w = 'helloworld\n'
print ss_w
print '写入字符长度',len(ss_w)
fe.write(ss_w) #
fe.close()
fe = open('testb.txt','rb') # 二进制读取
ss = fe.read()
print ss
print '读取字符长度',len(ss)
运行结果
helloworld
写入字符长度 11
helloworld
读取字符长度 12
常用的方法
read readline readlines
三个方法是常用的读取方法,都可以添加可选参数[size]。read方法不带参数默认是读取文件所有内容。readline是读取一行内容(如果一行里面有回车,包含回车内容)而readlines即是重复调用readline。多次读取文件中的内容,返回内容的一个字符串list
write writelines
write方法中没有writeline因为这个方法可以被write(content+\n)替代。writelines给定一个sequence,然后可以将这个sequence每一个元素当做一行写入到文件当中. 当然回车换行需要自己写入
se = ['hello\n','world\n']
fe = open('testa.txt','w')
fe.writelines(se)
fe.close()
fe = open('testa.txt','r')
ss = fe.readlines()
print ss
运行结果
['hello\n', 'world\n']
seek
该方法用于调节文件中读写操作的位置,基本描述如下
seek(offset[, whence]) -> None. Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
设置偏移位置与相对位置(相对于头部,尾部以及当前)与matlab等比较类似,不再赘述。