Py学习  »  Python

python docx attributeerror:“windowspath”对象没有“seek”属性

05x • 5 年前 • 1375 次点击  

我想在docx文件中插入大约250个带有文件名的图像。

我的 test.py 文件:

from pathlib import Path
import docx
from docx.shared import Cm

filepath = r"C:\Users\Admin\Desktop\img"
document = docx.Document()

for file in Path(filepath).iterdir():
#    paragraph = document.add_paragraph(Path(file).resolve().stem)
    document.add_picture(Path(file).absolute(), width=Cm(15.0))

document.save('test.docx')

在调试之后,我得到了这个错误:

Exception has occurred: AttributeError
'WindowsPath' object has no attribute 'seek'
  File "C:\Users\Admin\Desktop\test.py", line 10, in <module>
    document.add_picture(Path(file).absolute(), width=Cm(15.0))

我怎样才能避免这个错误?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43322
 
1375 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Book Of Zeus Servoo
Reply   •   1 楼
Book Of Zeus Servoo    6 年前

在我的例子中,将路径中的“/”改为“\”就成功了。例如:“c:/users/admin/desktop/img” (我相信用fileio包装可能就是这样,但在我的情况下,这样做是行不通的)

你也可以通过使用

os.path.join(mydir, myfile)

如本文所述 https://stackoverflow.com/a/2953843/11126742

wtee
Reply   •   2 楼
wtee    6 年前

你试过用 io.FileIO ?

from io import FileIO

from pathlib import Path
import docx
from docx.shared import Cm

filepath = r"C:\Users\Admin\Desktop\img"
document = docx.Document()

for file in Path(filepath).iterdir():
#    paragraph = document.add_paragraph(Path(file).resolve().stem)
    document.add_picture(FileIO(Path(file).absolute(), "rb"), width=Cm(15.0))

document.save('test.docx')

在将文件路径传递给pdffilereader时,我在使用pypdf2时遇到了相同的错误。当我把pdf文件打包时 FileIO 像这样 FileIO(pdf_path, "rb") 错误消失了,我成功地处理了这个文件。