首页 > 其他分享 >第十周

第十周

时间:2022-12-08 14:14:18浏览次数:32  
标签:庄园 第十 file print path message os

1.创建并打开记录蚂蚁庄园动态的文件

print("\n","="*10,"蚂蚁庄园动态","="*10)
file = open('message.txt','w')
print("\n即将显示\n")

 

 2.向蚂蚁庄园的动态文件写入一条信息

print("\n","="*10,"蚂蚁庄园动态","="*10)
file = open('message.txt','w')
file.write("你使用了一张加速卡,小鸡撸起袖子吃饲料,进食速度大大加快")
print("\n写入了一条动态…………\n")
file.close()

 

 

3.显示蚂蚁庄园的动态

print("\n","="*25,"蚂蚁庄园动态","="*25,"\n")
with open('message.txt','r') as file:
message = file.read()
print(message)
print("\n","="*29,"over","="*29,"\n")

 

 

4.逐行显示蚂蚁庄园的动态

print("\n","="*25,"蚂蚁庄园动态","="*25,"\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","="*25,"over","="*25,"\n")

 

 

5.遍历指定目录

import os
path = "D:\\mypython"
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))

 

 

6.获取文件基本信息

import os
fileinfo = os.stat("message.txt")
print("文件完整路径: ",os.path.abspath("message.txt"))
print("索引号: ",fileinfo.st_ino)
print("设备名: ",fileinfo.st_dev)
print("文件大小",fileinfo.st_size,"字节")
print("最后一次访问时间",fileinfo.st_atime)
print("最后一次修改时间",fileinfo.st_mtime)
print("最后一次动态变化时间",fileinfo.st_ctime)

 

 

实战一

import time
import os
now = time.localtime()
time_now = time.strftime("%Y-%m-%d-%H_%M",now)
path = "D:\shizhan\{}".format(time_now)
if not os.path.exists(path):
os.makedirs(path)
print("文件夹创建完成" + path)

 

 

实战二

批量添加文件夹

import os
path = r"D:\mypython"
s = 0
for i in range(4):
dirName = str(i)
os.makedirs(path + "\\" + dirName)
s += 1
s1 = str(s)
print("文件夹" + s1 +"创建成功!")

标签:庄园,第十,file,print,path,message,os
From: https://www.cnblogs.com/rweiq/p/16965913.html

相关文章