python文件操作脚本

一、统计目录下每个文件类型的数量

import os

# 定义存储结果
results = {}

# 返回所有文件组成的列表
all_files = os.listdir(os.curdir)

for file in all_files:
    if os.path.isdir(file):
        results.setdefault('directory', 0)
        results['directory'] += 1
    else:
        # 如果不是文件夹,而是文件,根据文件后缀进行类型统计
        file_type = os.path.splitext(file)[1].split(".")[1]
        results.setdefault(file_type, 0)
        results[file_type] += 1

二、指定目录搜索文件

import os


def search_file(directory,filename):
    #进入用户目录
    os.chdir(directory)

    #遍历
    for each_file in os.listdir(os.curdir):
        if each_file == filename:
            print(os.getcwd() + "\\" + each_file)
        elif os.path.isdir(each_file):
            search_file(each_file,filename) #递归调用
            os.chdir(os.pardir)             #返回上级目录

file_path = input("请输入搜索目录: ")
file_name = input("请输入搜索文件: ")
search_file(file_path,file_name)

三、指定目录模糊所搜文件

import os

def serch_file(filename,file_path):
    #进入指定路径
    os.chdir(file_path)

    #遍历目录
    for each_file in os.listdir(os.curdir):
        if os.path.isfile(each_file) and filename in each_file:
            print(os.getcwd() + os.sep + each_file)
        elif os.path.isdir(each_file):
            serch_file(filename,each_file)
            os.chdir(os.pardir)


serch_file('te','.')

四、根据商品信息进行权重分析统计

'''
权重: 价格: 0.1,评论: 0.4,星级:0.2,销量: 0.3
'''
goods = [
{"name":'g1','price': 200,'sales': 2000,'comments': 3420,'star': 4.5},
{"name":'g2','price': 242,'sales': 1890,'comments': 1240,'star': 4.7},
{"name":'g3','price': 69,'sales': 3200,'comments': 2110,'star': 4.8},
{"name":'g4','price': 130,'sales': 2700,'comments': 2670,'star': 4.9},
{"name":'g5','price': 179,'sales': 3100,'comments': 2780,'star': 4.6},
]

p = sorted(
    goods,key=lambda         x:x['price']*0.1+x['comments']*0.4+x["star"]*0.2+x["sales"]*0.3,reverse=True)
print(p)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值