打开文件:
f = open('yesterday2.txt', 'r+', encoding='utf-8') #文件句柄 读写
f = open('yesterday2.txt', 'w+', encoding='utf-8') #文件句柄 写读
f = open('yesterday2.txt', 'a+', encoding='utf-8') #文件句柄 追加读写
f = open('yesterday2.txt', 'rb', encoding='utf-8') #文件句柄 二进制文件
#with打开文件
with open("yesterday2.txt", "r", encoding="utf-8") as f:
for line in f:
print(line)
写:
f.write("我要去北京,看看长城")
读:
f = open('yesterday2.txt', 'r', encoding='utf-8')
1、data = f.read() #读取全文
2、print(f.readline()) #读一行
3、for line in f.readlines(): #将所有行读出来,遍历
print(line.strip())
4、for line in f:
print(line)
确定鼠标位置:
print(f.tell()) #tell按字符读取焦点位置
print(f.read(5))
print(f.tell())
#回到首焦点
f.seek(0)
f.encoding #查看文件的编码
f.fileno() #返回文件编号
修改文件:
# Author:dancheng
f = open('yesterday2.txt', 'r', encoding='utf-8') #文件句柄
f_new = open('yesterday2.txt.bak', 'w', encoding='utf-8')
for line in f:
if "position" in line:
line = line.replace("position", "单程")
f_new.write(line)
f.close()
f_new.close()