文件穿件

>>> with open(r'C:\Users\lhq\Desktop\haha.txt','r+') as f:           
f.seek(7)
f.write('l+++')

7
4

f.read(10) 读10行

f.tell() 读取当前光标位置

#这个语句可以自动关闭句柄,使用中r为可读w为写,但w没有这个文件创建文件,文件存在的话会覆盖掉这个文件(使用需当心)建议使用‘r+’, 或者a

f.seek(7) 文件访问至第7个字符开始,0,就是回到开始,与a不能共用,a为append追加到末尾

 f.truncate() 截断文件,默认清除所有,加入字符数,保留多少个字符开始清除, f.truncate(20) 保留前面20个字符,前提是打开文件不能用w模式,用a 

a.flush() 立即刷新文件,默认一次性写入内存,当需要一次更改后立刻刷新,可以使用这个方法,参看rpm包进度条中的a.flush()方法

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a stream. Raise IOError upon failure.

-------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)

猜你喜欢

转载自www.cnblogs.com/len1028/p/9230138.html