问题描述
在一个python项目中,我需要在运行脚本中访问位于同一工程不同目录下的一份空表格文档文件,并将填入数据的表格放入另一目录中。
项目目录示例如下:
project/
│
├── resource/
│ └── module/
│ └── form.docx # 需访问文件
│ └── output/ # 输出文件目录
│
├── app/
│ └── server.py # 运行脚本
原函数代码
def fill_template(data, form_type):
"""
将数据填入Word文档中的表格中。
:param data: 包含要填充数据的字典
:param form_type: 表格类型名称(如 "旁站", "巡视")
"""
empty_form_path = 'resource/module/'+form_type+'.docx'
print(empty_form_path)
if not os.path.exists(empty_form_path):
print("文档未找到")
return
doc = Document(empty_form_path)
tables = doc.tables
if not tables:
print("文档中没有表格")
return
sample_font_size = get_sample_font_size(tables[0])
fill_table(tables[0], data, sample_font_size)
output_path = 'resource/output/' + form_type + '输出.docx'
if os.path.exists(output_path):
os.remove(output_path)
doc.save(output_path)
print(f"Document saved as {output_path}")
原运行脚本的方式为:
D:\Project> cd app
D:\Project\app> python server.py
解决方案
相对路径 (relative path) 访问是相对于当前工作目录(即运行脚本的目录)定义的文件或文件夹路径,而非系统的根目录开始的绝对路径/脚本所在目录。
原本运行脚本方式的工作目录为:D:/Project/app,无法访问 resource/module/
因此需改变工作目录至工程根目录。
正确运行方式:
D:\Project> python app/server.py
此时工作目录为:D:/Project,能顺利访问 resource/module/