如果我们向文件中写入数据的话,我们可以使用write()函数。
写文件:
#打开文件 f = open("./index.cpp","w") #1. 写入数据 contents = "hello world!" write(contents) #关闭文件 f.close() |
文件定位:
函数名 | 含义 |
f.tell() | 返回文件当前位置 |
f.seek(off,from) | 设置位置为from位置偏移off的位置 from可选为:0文件开始 1当前位置 2文件末尾位置 |
#coding=utf-8
#打开文件 f = open("./test.txt","rb")
#输出文件当前位置 print(f.tell())
#当我读了两字节之后 f.read(2)
#输出结果为2 print(f.tell())
#将文件位置设置到第5个位置 f.seek(5,0) print(f.read())
#将文件位置设置到文件倒数三个字符位置 #在py3中,如果不是以b模式打开文件,只允许从开始位置设置位置 #不允许从末尾偏移0-文件头,默认值;1-当前位置;2-文件尾 f.seek(-3,2) contents = f.read() print(chr(contents[0])) print(contents)
#关闭文件 f.close() |