xwb123

导航

第十章

实例01--创建并打开记录蚂蚁庄园动态文件

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

 

 

 

 

 

 实例02--向蚂蚁庄园的动态文件写入一条信息

print('\n','='*10,'蚂蚁庄园动态','='*10)
file=open('message.txt','a')
#追加一条动态信息
file.write('mingri的小鸡在你的庄园待了22分钟,吃了6g饲料之后,被你赶走了。\n')
print('\n追加了一条动态。。。\n')
file.close()

 

 实例03--现实蚂蚁庄园的动态

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

 

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

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')

 

 实例05--遍历指定目录

import os
path='C:\\demo'  #指定要遍历的根目录
print('',path,'】目录下包括的文件和目录:')  
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))

实例06--获取文件基本信息

import os
fileinfo=os.stat('xiazaizhiyuan.pythontest')
print('文件完整路径:',os.path.abspath('xiazaizhiyuan.pyhtontest'))
#输出文件的基本信息
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
while True:
    try:
        count=int(input('请输入需要生成的文件数:'))
        break
    except Exception as e:
        print('输入有误,请输入正确的数字!')
for i in range(count):
    file_name=time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))+'.txt'
    print('file%d:%s'%((i+1),file_name))
    print('生成文件成功!')
    with open(file_name,'w') as file:
        time.sleep(1)

 

 

 

实战二:批量添加文件夹

import os
import shutil
while True:
    try:
        count=int(input('请输入需要生成的文件夹个数:'))
        break
    except Exception as e:
        print('输入有误,请输入正确的数字!')
path='10-2' #这是相对路径‘d:/10-2'是绝对路径
if os.path.exists(path):  #判断目录是否存在、删除和遍历目录
    shutil.rmtree(path)
for i in range(count):
    os.makedirs(os.path.join(path,str(i+1)))
    print('',i+1,'个文件夹,创建成功!')
    

 

 

 

posted on 2022-12-14 20:47  雪人头子  阅读(22)  评论(0编辑  收藏  举报