2016-10-13 136 views
0

我需要從給定文件夾和子文件夾中提取文件名(圖號)。然後,我需要對照包含圖紙編號列表和相應圖紙描述的Excel文件,交叉查找所找到的圖形編號列表。輸出需要是包含兩列的Excel表格,用於圖號和圖形說明。在20個文件夾和子文件夾中有大約500個圖紙需要遍歷。在文件夾中查找文件名並匹配到Excel表

回答

2

walk from os模塊可能會很有幫助,因爲csv模塊可以讓excel讀取文件。沒有更多的細節,我只能給你一個粗略的骨架。在下文中,root是包含所有你想要搜索的目錄的頂級目錄:

import os 
import csv 

#The below is sample code for reading your existing csv files. 
#It will vary based on their exact specifications 

with open('myfile.csv', newline='') as f: 
    reader = csv.reader(f) 
    d = {line[0]: line[1] for line in reader} 

#Next is code for opening the output file, 
#then going through all the filenames in our directory 
#For each filename, we look it up in the dictionary from earlier 
# then write that pair to the output file 

with open('output.csv', 'w+', newline='') as out: 
    writer = csv.writer(out) 
    for dirpath, dirnames, filenames in os.walk('root'): 
     for filename in filenames: 
      writer.writerow([filename, d[filename]) 

我建議你查查csv和Python官方文檔os.walk

+0

非常感謝@Patrick哈夫 – Jup

+0

該死的我打回車 - 我會看看相關的文件。但是,一個簡單的問題是,'myfile.csv'是否應該是一個現有的文件?我還得到了錯誤文件「C:/用戶/ jeanpaul /桌面/測試2.py」,第7行,在 與開放('myfile.csv',新行='')爲f: TypeError:'newline '是這個函數的無效關鍵字參數 – Jup

+0

@Jup你使用的是什麼版本的Python? 'myfile.csv'應該是你已有的excel文件。我還沒有使用'csv'模塊,所以你可能需要使用一些選項來讓它和excel一起玩,儘管我知道它可以。 –

相關問題