python处理文件存储路径的坑

本次目标是在excel中找到代码文件中学生对应分数,并将其放到特定分数的文件夹下。
先贴上源码单纯记录处理过程:

# 导入openpyxl模块
from openpyxl import load_workbook
# 导入shutil模块和os模块
import os
import shutil

# 加载excel
wb = load_workbook('~~.xlsx')
# 加载 sheet
ws = wb["Sheet1"]
# 源文件的绝对路径
src_dir_path = 'D:\\~\\~\\~~'
# 目标文件的绝对路径
to_dir_path = 'D:\\~\\~\\--'
# 当前文件夹下的文件list
filelist = os.listdir(src_dir_path)

# 遍历原文件夹中的所有同学文件夹
for file in filelist:
    sub_path = os.path.join(src_dir_path, file)  # 获取文件的绝对路径

    # 遍历excel中的学生名单
    for i in range(1, 421):
        # 获取单元格内的值
        student_name = ws['D' + str(i)].value
        q1 = ws['G' + str(i)].value
        q2 = ws['H' + str(i)].value
        # print(student_name, '+', q1, '+', q2)
        # 如果文件夹名称中匹配到了student_name字符串
        if student_name in file:
            subfilelist = os.listdir(sub_path)
            for subfile in subfilelist:
                print(subfile)
                # 如果文件名称中匹配到了'1.'字符串
                if '1.' in subfile:
                    # 如果第一题分数小于100
                    if q1 < 100:
                        path1 = os.path.join(to_dir_path, "1_"+str(q1))
                        is_exists = os.path.exists(path1)
                        # 判断路径是否存在 不存在则建立一个
                        if not is_exists:
                            os.makedirs(path1)
                        path1_1 = os.path.join(sub_path, subfile)
                        path1_2 = os.path.join(to_dir_path, "1_"+str(q1), file+"_"+subfile)
                        print(path1_1)
                        print(path1_2)
                        # 将源路径文件拷贝到目标路径下
                        shutil.copy(path1_1, path1_2)
                elif '2.' in subfile:
                    if q2 < 100:
                        path2 = os.path.join(to_dir_path, "2_" + str(q2))
                        is_exists = os.path.exists(path2)
                        if not is_exists:
                            os.makedirs(path2)
                        path2_1 = os.path.join(sub_path, subfile)
                        path2_2 = os.path.join(to_dir_path, "2_" + str(q2), file + "_" + subfile)
                        print(path2_1)
                        print(path2_2)
                        shutil.copy(path2_1, path2_2)

os.path.join这个函数,如果用逗号则表示使用路径形式连接,用加号则是使用字符串形式连接,如:

os.path.join("hello", "world" + "ddd", "ddd")
# 表示路径\hello\worldddd\ddd

os.path.join("hello", "\world" + "ddd", "ddd")
# 表示路径\worldddd\ddd
# 不会显示\hello

话说python真的太赞了,处理文件神器~

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值