2016-10-13 138 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一起玩,尽管我知道它可以。 –

相关问题