实例一:创建并打开记录蚂蚁庄园动态的文件
实验代码:
print("\n","="*10,"蚂蚁庄园动态","="*10) file = open('message.txt','w') print("\n 即将显示……\n")
实验结果:
实例二:向蚂蚁庄园的动态文件写入一条信息
实验代码:
print("\n","="*10,"蚂蚁庄园动态","="*10) file = open('message2.txt','w') #写入一条动态信息 file.write("你使用了1张加速卡,小鸡撸起袖子开始双手吃饲料,进食速度大大加快。\n") print("\n 写入了一条动态……\n") file.close()
实验结果:
实例三:显示蚂蚁庄园的动态
实验代码:
print("\n","="*25,"蚂蚁庄园动态","="*25,"\n") with open('message3.txt','r') as file: message3 = file.read() print(message3) print("\n","="*29,"over","="*29,"\n")
实验结果:
实例四:逐行显示蚂蚁庄园的动态
实验代码:
print("\n","="*35,"蚂蚁庄园动态","="*35,"\n") with open('message3.txt','r') as file: number = 0 while True: number +=1 line = file.readline() if line == '': break print(number,line,end= "\n") print("\n","="*39,"over","="*39,"\n")
实验结果:
实例五:遍历指定目录
实验代码:
import os path = "D:\\pyprogram\\第九章" print("【",path,"】 目录下包括的文件和目录:") for root, dirs, files in os.walk(path, topdown=True): for name in dirs: print("⚫",os.path.join(root, name)) for name in files: print("◎",os.path.join(root, name))
实验结果:
实例六:获取文件基本信息
实验代码:
import os fileinfo = os.stat("10-1.py") #获取文件的基本信息 print("文件完整路径:",os.path.abspath("10-1.py")) #获取文件的完整数路径 #输出文件的基本信息 print("索引号:",fileinfo.st_ino) print("设备名:",fileinfo.st_dev) print("文件大小:",fileinfo.st_size,"字节") print("最后一次访问时间:",fileinfo.st_atime) print("最后一次修改时间;",fileinfo.st_mtime) print("最后一次状态变化时间;",fileinfo.st_ctime)
实验结果:
标签:庄园,Python,第十章,实验,file,print,fileinfo,os From: https://www.cnblogs.com/zhuangzhuang123/p/16924977.html