2013-07-23 56 views
0

我有一個非常簡單的任務,但我沒有用python中的excel做太多的功能,我不知道如何去做這件事。用Python重命名和保存Excel文件

我需要做什麼:

要看很多出類拔萃的子文件夾中的文件,根據文件中的信息將其重命名,並將它們全部存儲在一個文件夾在別處英寸

的數據結構是這樣的:

主文件夾

Subfolder1

File1中

文件2

文件3

...

對於每個子文件夾內約一百子文件夾和一些文件。

從這裏,我想從文件中提取公司名稱,零件號和日期,並使用它們重命名excel文件。不知道如何重命名文件。

然後將它保存在別的地方。我無法找到所有這些功能,有什麼建議嗎?

+0

你能從文件中提取公司名稱等嗎?即您的問題是關於重命名還是關於從文件中獲取數據?另外,你有什麼嘗試? –

回答

1

檢查osos.path模塊上市文件夾的內容(walklistdir),並與路徑名(abspathbasename等)

工作同時,shutil有複製的東西了一些有趣的功能。檢出copyfile並根據您從Excel文件中讀取的數據指定dst參數。

此頁面可以幫助你獲得在Excel數據:http://www.python-excel.org/

你可能希望有一些高水平這樣的代碼:

for subfolder_name in os.listdir(MAIN_FOLDER): 
    # exercise left to reader: filter out non-folders 
    subfolder_path = os.path.join(MAIN_FOLDER, subfolder_name) 
    for excel_file_name in os.listdir(os.path.join(MAIN_FOLDER, subfolder_name)): 
     # exercise left to reader: filter out non-excel-files 
     excel_file_path = os.path.join(subfolder_path, excel_file_name) 
     new_excel_file_name = extract_filename_from_excel_file(excel_file_path) 
     new_excel_file_path = os.path.join(NEW_MAIN_FOLDER, subfolder_name, 
      new_excel_file_name) 
     shutil.copyfile(excel_file_path, new_excel_file_path) 

你必須使用xlrd模塊提供extract_filename_from_excel_file自己從我提到的網站。

+0

看起來不錯 - 我正在寫它。一個問題: 在「對於os.list中的excel_file_name ...」是「子文件夾」子文件夾名稱或子文件夾路徑? – user2417886

+0

我也很難搞清楚xlrd。有什麼建議麼? – user2417886

+0

FTFY:它是'subfolder_name'。至於'xlrd',我自己沒有太多經驗。看看這樣的教程:http://www.youlikeprogramming.com/2012/03/examples-reading-excel-xls-documents-using-pythons-xlrd/ –