零基础学python 第十章

实例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("你使用了1张加速卡,小鸡撸起袖子开始双手吃饲料,进食速度大大加快。\n")
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")

运行结果

 ========================= 蚂蚁庄园动态 ========================= 

你使用了1张加速卡,小鸡撸起袖子开始双手吃饲料,进食速度大大加快。


 ============================= over ============================= 

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

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 ======================================= 

实例5 遍历指定目录

import os
path = "c:\\demo"
print("",path,"】目录下包含1的文件和目录:")
for root, dirs,file 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:\demo 】目录下包含1的文件和目录:

实例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)

运行结果

文件完整路径: E:\pycharmprojects\message.txt
索引号: 1970324837009530
设备名: 1679891863
文件大小: 67 字节
最后一次访问时间: 1667455028.4735076
最后一次修改时间: 1667454390.5205727
最后一次状态变化时间: 1667453820.9327476

实战一 根据当前时间创建文件

import time
import os
import datetime
num = int(input("请输入需要生成的文件数:"))
for i in range (num):
    # 获取当前时间
    t = datetime.datetime.now()

    path = "E:\pycharmprojects"
    # 对现在的时间格式化,作为文件名
    file = os.path.join(path, t.strftime('%Y%m%d%H%M%S')+'.txt')
    open(file, 'w')
    time.sleep(1)   #休眠1s
    i += 1
    print("file " + str(i) + ":" + str(file))
print("生成文件成功!")

运行结果

请输入需要生成的文件数:2
file 1:E:\pycharmprojects\20221109160402.txt
file 2:E:\pycharmprojects\20221109160403.txt
生成文件成功!

实战二:批量添加文件夹

import os
num = int(input("请输入需要生成的文件数:"))
for i in range(num):
    path = "E:\pycharmprojects"
    if not os.path.exists('{}'.format(i + 1)):
        os.mkdir('{}'.format(i + 1))
        print("文件夹{}".format(i + 1) + "创建成功!")

运行结果

请输入需要生成的文件数:4
文件夹1创建成功!
文件夹2创建成功!
文件夹3创建成功!
文件夹4创建成功!
posted @ 2022-11-09 16:12  21信计1朱美怡  阅读(29)  评论(0)    收藏  举报