请求帮忙解决Python编程中提示路径错误文档不能写入的问题?

请求帮忙解决Python编程中提示路径错误文档不能写入的问题?

我想实现的功能是:将n张图片拖入固定文件夹中后自动用word排版,word标题为“照片”,每页排版两张照片,每张照片下边有序号和“备注:”

import os

from PIL import Image

from docx import Document

from docx.shared import Inches

from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

from docx.oxml import OxmlElement

def create_word_document(image_folder, output_path):

# 获取图片文件列表

image_files = [f for f in os.listdir(image_folder) if f.lower().endswith(('.jpg', '.jpg', '.jpeg', '.gif', '.bmp'))]

if not image_files:

print("未找到任何图片文件。")

return

# 创建Word文档

doc = Document()

doc.add_heading('照片', level=1).alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

# 每页排版两张照片

photos_per_page = 2

for i, image_file in enumerate(image_files, start=1):

if i % photos_per_page == 1:

# 添加新的一页

section = doc.sections[-1]

footer = section.footer

footer.paragraphs[0].clear() # 清除页脚原有内容

footer.paragraphs[0].add_run(f"第 {i // photos_per_page + 1} 页").alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

doc.add_page_break()

# 添加图片和备注

img_path = os.path.join(image_folder, image_file)

img = Image.open(img_path)

doc.add_picture(img_path, width=Inches(3.0))

doc.add_paragraph(f"序号:{i}")

doc.add_paragraph("备注:")

# 保存Word文档

doc.save(output_path)

print(f"Word文档已保存至: {output_path}")

if __name__ == "__main__":

# 指定图片文件夹和输出Word文档路径

image_folder_path = "d:ANZHUANG/PYTHON/IMA"

output_word_path = "d:ANZHUANG/PYTHON/output/"

create_word_document(image_folder_path, output_word_path)

为什么运行的时候老是出现写入路径错误

D:\ANZHUANG\PYTHON\python.exe C:/Users/admin/PycharmProjects/pythonProject/lianxi3.py

Traceback (most recent call last):

File "C:\Users\admin\PycharmProjects\pythonProject\lianxi3.py", line 51, in <module>

create_word_document(image_folder_path, output_word_path)

File "C:\Users\admin\PycharmProjects\pythonProject\lianxi3.py", line 40, in create_word_document

doc.save(output_path)

File "D:\ANZHUANG\PYTHON\lib\site-packages\docx\document.py", line 151, in save

self._part.save(path_or_stream)

File "D:\ANZHUANG\PYTHON\lib\site-packages\docx\parts\document.py", line 106, in save

self.package.save(path_or_stream)

File "D:\ANZHUANG\PYTHON\lib\site-packages\docx\opc\package.py", line 151, in save

PackageWriter.write(pkg_file, self.rels, self.parts)

File "D:\ANZHUANG\PYTHON\lib\site-packages\docx\opc\pkgwriter.py", line 27, in write

phys_writer = PhysPkgWriter(pkg_file)

File "D:\ANZHUANG\PYTHON\lib\site-packages\docx\opc\phys_pkg.py", line 109, in __init__

self._zipf = ZipFile(pkg_file, "w", compression=ZIP_DEFLATED)

File "D:\ANZHUANG\PYTHON\lib\zipfile.py", line 1239, in __init__

self.fp = io.open(file, filemode)

PermissionError: [Errno 13] Permission denied: 'd:ANZHUANG/PYTHON/output/'

通过提高管理员权限试图解决不能写入给定路径的问题,但是还是出现结果中的提示。
希望大神帮忙指点一下,如何实现既定的功能。


回答:

盘符后面的路径分隔符漏了, d:/ANZHUANG/PYTHON/output/


回答:

放linux环境用root权限执行试试

以上是 请求帮忙解决Python编程中提示路径错误文档不能写入的问题? 的全部内容, 来源链接: utcz.com/p/939099.html

回到顶部