实例一:创建并打开记录蚂蚁庄园动态的文件
- 代码:
print("\n","="*10,"蚂蚁庄园动态","="*10)
file = open('message.txt','w')
print("\n 即将显示……\n")
- 结果:
========== 蚂蚁庄园动态 ==========
即将显示……
实例二:向蚂蚁庄园的动态文件写入一条信息
- 代码:
print("\n","="*10,"蚂蚁庄园动态","="*10)
file = open('message.txt','w')
#写入一条动态信息
file.write("你使用了1张加速卡,小鸡撸起袖子开始双手吃饲料,进食速度大大加快。\n")
print("\n 写入了一条动态……\n")
file.close()
- 结果:
========== 蚂蚁庄园动态 ==========
写入了一条动态……
实例三:显示蚂蚁庄园的动态
- 代码:
print("\n","="*10,"蚂蚁庄园动态","="*10)
file = open('message.txt','w')
print("\n 即将显示……\n")
- 结果:
========================= 蚂蚁庄园动态 =========================
你使用了1张加速卡,小鸡撸起袖子开始双手吃饲料,进食速度大大加快。
============================= over =============================
实例四:逐行显示蚂蚁庄园的动态
- 代码:
print("\n","="*35,"蚂蚁庄园动态","="*35,"\n")
with open('message.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")
- 结果:
=================================== 蚂蚁庄园动态 ===================================
1 你使用了1张加速卡,小鸡撸起袖子开始双手吃饲料,进食速度大大加快。
======================================= over =======================================
实例五:遍历指定目录
- 代码:
import os
path = "C : \\demp"
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))
- 结果:
【 C : \demp 】 目录下包括的文件和目录:
实例六:获取文件基本信息
- 代码:
import os
fileinfo = os.stat("mr.png")
print("文件完整路径:",os.path.abspath("mr.png"))
#输出文件的基本信息
print("索引好:",fileinfo.st_ino)
print("设备名:",fileinfo.st_dev)
print("文件大小:",fileinfo.st_size,"字节")
print("最近一次访问时间:",fileinfo.st_atime)
print("最近一次修改时间:",fileninfo.st_mtime)
print("最后一次状态变化时间:",fileinfo.st_ctime)
- 结果:
实战一:根据当前时间创建文件
- 代码:
import time
def create():
global name
localTime = time.strftime("%Y%m%d%H%M%S",time.localtime())
name = localTime + '.txt'
with open(name,'a') as file:
pass
if __name__ == '__main__':
amount = int(input('请输入需要生成的文件数:'))
for i in range(amount):
create()
print('file' + str(i+1) + ':' +name)
time.sleep(1)
print('生成文件成功!')
- 结果:
请输入需要生成的文件数:3
file1:20221109174722.txt
file2:20221109174723.txt
file3:20221109174724.txt
生成文件成功!
实战二:批量添加文件夹
- 代码:
import os
path = 'E:/22 mypython/dishizhang'
amount = int(input('请输入需要生成的文件数:'))
for i in range(amount):
isExists = os.path.exists(path+str(i))
if not isExists:
newdir = 'LIDC-%04d'%i
print(newdir)
os.makedirs(path+newdir)
print("文件夹 %s 创建成功!"%i)
else:
print("文件夹 %s 已经存在!"%i)
continue
- 结果:
请输入需要生成的文件数:1
LIDC-0000
文件夹 0 创建成功!
标签:文件,庄园,name,第十章,file,print,path,os,目录 From: https://www.cnblogs.com/tftfboys/p/16875810.html