我想将约250张图像及其文件名插入docx文件。
我的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))
如何避免此错误?
最佳答案
您是否尝试过使用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
中时,错误消失了,我能够成功处理该文件。关于python - Python docx AttributeError:“WindowsPath”对象没有属性“seek”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53591660/