我在需要更新元数据的文件夹和子文件夹中有大约300个docx文件。我有一个单独的包含元数据的300多行csv文件:每行包含文件名,关键字和行中的标题。使用python-docx更新大量文件的docx元数据
我想循环浏览从csv提取内容并将元数据插入docx文件的docx文件。 Docx文件从根文件夹向下存储2个子文件夹。
到目前为止,我已经勾画出以下内容。我正在努力研究如何循环访问csv文件并按顺序将元数据应用于每个文件。我确信有一个相对简单的方法可以解决这个问题,建立循环并获取csv内容就是我迷失的地方。我是一个小菜鸟,和我一样,感受我的方式。
任何提示赞赏。
#running in python 3.5.2 32bit
import csv
from docx import Document
import os
import sys
csv_path = ("datasheet_metadata_uplift.csv")
def update_docx_metadata(document, keywords, title):
"""
Update the *keywords*, and *title* metadata
properties in *document*.
"""
core_properties = document.core_properties
core_properties.keywords = keywords
core_properties.title = title
def read_csv_lines(filename, keywords, title):
"""
Reads the csv lines, returns *filename*, *keywords*, *title*
"""
with open(csv_path, 'r') as f:
csv_file = csv.reader(f)
for row in csv_file:
filename = row[0]
keywords = row[1]
title = row[2]
def open_docx(filename):
"""
Search for docx file and open it
"""
for root, dirs, files in os.walk("."):
if filename in files:
doc_path = os.path.join(path, filename)
csv_lines = read_csv_lines(filename, keywords, title)
for filename, keywords, title in csv_lines:
document = Document(doc_path)
update_doc_metadata(filename, keywords, title)
document.save(doc_path)
嗨Scanny - 谢谢!非常有帮助的答案,我一直在重构使用函数,如你所建议的,但有些不太正确。我得到一个'NameError:name'文件名'未定义'的错误与代码的最后部分有关。我已经使用新代码更新了原始帖子。 有什么想法? – Aidan
@Aidan我想你可能会对函数参数在Python中的作用感到困惑。他们将价值(*)*转化为*函数,但通常不会*出*。为此你需要一个return语句。所以read_csv_lines应该只是将csv_path作为参数,然后返回(filename,keywords,title)序列(可能是元组)的序列(可能是list)。我认为read_csv_lines的返回值只是'return [row for csv_file]''。您可能想要查找一些Python教程资源。我喜欢[这一个](https://pymotw.com/3/)和Python官方教程是相当不错:) – scanny
好吧,感谢您的帮助scanny,我意识到,我今天看到这一点。 – Aidan