Python自動化辦公p2: 遍歷/搜索文件/查詢文件信息

import os

#1-遍歷:os.walk(指定的絕對路徑或相對路徑):把文件夾裏的文件夾裏的文件都找出來

for dirpath,dirnames,files in os.walk('./'):
    print(F"發現文件夾:{dirpath}")
    print(files)

#2-搜索:  (1)利用字符串匹配方法
#.starswith() .endswith()
print('meanwhile'.startswith('mean'))
print('meanwhile'.endswith('ile'))

#          (2) glob模塊 glob.glob() recursive=True 遞歸找到文件夾下的所有符合條件文件

import glob
print(glob.glob('*.py'))# *任意的字符
print(glob.glob('test_?.py'))# ?單個字符
print(glob.glob('test_[2,5].py')) # []列表內的匹配 [0-9] [1,4,5] ![1,3]不在列表內的
print(glob.glob('**/*.pth', recursive=True))

#           (3)fnmatch模塊 可以用來匹配文件名

import fnmatch
print(fnmatch.fnmatch('test.py','te*.py'))

#3-查詢文件信息;  os.scandir()返回的文件都可以查詢信息
#                files.stat()文件的信息 st_size st_mtime
#                os.stat(指定文件路徑)單獨查詢制定文件信息
#                time.ctime()
#                datetime.datetime.fromtimestamp()
import time #unix時間戳 time.ctime()
import datetime #時間戳

that_time = datetime.datetime.fromtimestamp(1567764428)
print(that_time)
print(that_time.year,that_time.day)
print(that_time.hour)
print(that_time.minute)
print(that_time.second)

for files in os.scandir():
    files_time = files.stat().st_mtime
    print(files.name,datetime.datetime.fromtimestamp(files_time))

print(os.stat('test_1.py'))
#作業: 找到文件夾內體積大於100,以‘.py’結尾的文件
#       篩選文件日期早於2022年 輸出文件路徑
for ins in os.scandir():
    in_size = ins.stat().st_size
    in_time = datetime.datetime.fromtimestamp(ins.stat().st_mtime)
    in_time_year = in_time.year
    if in_size > 100 and ins.name.endswith('.py') and in_time_year<2022 :
        print(ins.path)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章