Python 在文件夹中查找文件名并与Excel表匹配
我需要从给定文件夹和子文件夹中提取文件名(图纸编号)。然后,我需要对照包含图纸编号列表和相应图纸说明的Excel文件交叉引用找到的图纸编号列表。输出需要是一个Excel表格,其中包含两列,分别是图纸编号和图纸说明。在20个文件夹和子文件夹中大约有500个图形需要遍历。Python 在文件夹中查找文件名并与Excel表匹配,python,excel,windows,Python,Excel,Windows,我需要从给定文件夹和子文件夹中提取文件名(图纸编号)。然后,我需要对照包含图纸编号列表和相应图纸说明的Excel文件交叉引用找到的图纸编号列表。输出需要是一个Excel表格,其中包含两列,分别是图纸编号和图纸说明。在20个文件夹和子文件夹中大约有500个图形需要遍历。os模块中的walk可能会很有帮助,用于使文件excel可以读取的csv模块也会很有帮助。没有更多的细节,我只能给你一个粗略的骨架。在以下目录中,root是顶级目录,其中包含要搜索的所有目录: import os import cs
os
模块中的walk可能会很有帮助,用于使文件excel可以读取的csv
模块也会很有帮助。没有更多的细节,我只能给你一个粗略的骨架。在以下目录中,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])
我建议您在官方Python文档中查找
csv
和os.walk
,从os
模块中查找walk
可能会很有帮助,因为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])
我建议您在官方Python文档中查找
csv
和os.walk
,Dammit我点击回车键-我将浏览相关文档。一个简单的问题是,“myfile.csv”在打开时是否应该是一个现有文件?我还得到了错误文件“C:/Users/jeanpaul/Desktop/test 2.py”,第7行,带有open('myfile.csv',newline=''),因为f:TypeError:'newline'是一个无效的关键字参数function@Jup您使用的是什么版本的pythonmyfile.csv
应该是您已有的excel文件。我没有经常使用csv
模块,因此您可能需要使用一些选项,以使其与excel配合使用,尽管我知道它可以。该死,我按了enter键-我将查看相关文档。一个简单的问题是,“myfile.csv”在打开时是否应该是一个现有文件?我还得到了错误文件“C:/Users/jeanpaul/Desktop/test 2.py”,第7行,带有open('myfile.csv',newline=''),因为f:TypeError:'newline'是一个无效的关键字参数function@Jup您使用的是什么版本的pythonmyfile.csv
应该是您已有的excel文件。我没有经常使用csv
模块,因此您可能需要使用一些选项,以使其与excel配合使用,尽管我知道它可以。