我在一個檔案夾中有一個 .pdf 檔案,我有一個帶有兩列的 .xls。在第一列中,我有不帶擴展名 .pdf 的檔案名,在第二列中,我有一個值。
我需要打開檔案 .xls,將第一列中的值與檔案夾中的所有檔案名匹配,然后將每個檔案 .pdf 重命名為第二列中的值。
可能嗎?
感謝您對安杰洛的支持
uj5u.com熱心網友回復:
您需要在 python 中使用 pandas 庫。它有一個函式pandas.read_excel,對于讀取 excel 檔案非常有用。這將回傳一個資料框,允許您使用iloc或其他方法訪問第一列和第二列中的值。從那里,我建議使用os.rename(old_name, new_name),其中 old_name 和 new_name 是保存 .pdf 檔案的路徑。重命名部分的完整示例如下所示:
import os
# Absolute path of a file
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
# Renaming the file
os.rename(old_name, new_name)
我故意省略了完整的解釋,因為您只是詢問是否有可能完成您的任務,所以希望這會為您指明正確的方向!根據stackoverflow 指南,我建議將來使用特定的可重現代碼提出問題。
uj5u.com熱心網友回復:
我鼓勵您使用 .csv 檔案而不是 xls 來執行此操作,因為這是一種更簡單的格式(需要 0 格式的邊框、顏色等)。
您可以使用 os.listdir() 函式列出某個目錄中的所有檔案和檔案夾。檢查 os 內置庫檔案。然后獲取每個檔案的字串名稱,洗掉 .pdf,并讀取包含名稱和值的 .csv 檔案,然后重命名檔案。
所需的所有實用程式都是內置的python。大多數是 os lib,其他只是來自 csv lib 和檔案的正常打開:
with open(filename) as f:
#anything you have to do with the file here
#you may need to specify what permits are you opening the file with in the open function
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/493610.html
