前面几篇介绍了文件的方法open和with open,属性read,write,close。下面是文件的其他属性。
1. f.tell(),返回文件当前位置
tell() 方法返回文件的当前位置,即文件指针指向位置, 决定了后续的读写操作。
-
r只读模式下,文件指针位置是0, 即文件的开头,读取所有内容后,文件指针位置是3, 即文件的末尾 -
a追加写入模式下,文件指针位置是7, 即文件的末尾,后面当然也读取不到任何内容
with open('file.txt', 'r') as f:
print(f.tell())
print(repr(f.read()))
with open('file.txt', 'a') as f:
print(f.tell())
# testing
0
'Hello!\n'
7
2. f.seek(offset[, whence]),设置文件当前位置
-
offset -- 开始的偏移量,也就是代表需要
移动偏移的字节数 -
whence:可选,默认值为 0。给offset参数一个定义,表示要
从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。 -
如果操作成功,则返回新的文件位置,如果操作失败,则函数返回 -1
with open('file.txt', 'a+') as f:
print(f.tell())
print(f.read())
print(f.seek(0, 0))
print(f.read())
print(f.seek(4, 0))
print(f.read())
# testing
50
0
The following functions operate on a history file.
4
following functions operate on a history file.
3. f.truncate( [ size ]),用于截断文件
- 指定长度的话,就从文件的开头开始
截断指定长度,其余内容删除 - 不指定长度的话,就从文件开头开始
截断到当前位置,其余内容删除 - 返回截断的字节长度
注意:
- 该方法需要
写的模式才可使用, 否则上报错误UnsupportedOperation: File not open for writing 文件的内容会被修改
with open('file.txt', 'r+') as f:
print(f.read())
f.seek(4, 0)
print(f.truncate())
f.seek(0, 0)
print(f.read())
# testing
The following functions operate on a history file.
4
The
4. f.flush(),用来刷新缓冲区的,直接把内部缓冲区的数据立刻写入文件
flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。
一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。
In [98]: f = open('a.txt', 'w+')
In [99]: f.read()
Out[99]: ''
In [100]: f.write('qwert')
Out[100]: 5
In [101]: cat a.txt
In [102]: f.flush()
In [103]: cat a.txt
qwert
In [104]: f.close()










网友评论