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真的太讚了,處理文件神器~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章