python处理文件存储路径的坑

    技术2025-05-20  43

    本次目标是在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真的太赞了,处理文件神器~

    Processed: 0.012, SQL: 12