python文件操作

# -*- coding: utf-8 -*-
#打开一个文件并读取内容
#data=open("yesterday",encoding="utf-8").read()
#打开一个文件并t添加文件句柄,并且标定打开文件模式,变量f
# w为写模式,创建新文件,原文件被替换,w只可写不可读 w+可写可读
# r为读模式,只可读不可写
# aappend模式,追加,追加在文件最后,不会删除之前内容,只可追加不可读,a+可写可读
# rb为二进制文件
import time
import sys
f=open("yesterday","r+",encoding="utf-8")
f.write(" alallalalal ")
#读前5
#根据角标判断行数,10行停止打印
for index,line in enumerate (f.readlines()):
if index==10:
print("已经打印",index,"")
continue
print(line.strip())

for i in range(5):
print(f.readline())
#可针对f对文件进行操作
#print(f.read())

#打印一行
f.readline()
#打印当前行数
print(f.tell())
#回到第一行
print(f.seek(0))
#返回文件句柄的编号
print(f.fileno())
#打印文件名
print(f.name)
#截断,从头开始截10个字符
f.truncate(10)
#stdout标准输出,输出到当前屏幕,通过stdout.write+flush打印进度条
for i in range(10):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(1)
原文地址:https://www.cnblogs.com/hekaiqiaq/p/8853858.html