How can i work with templates in Python-pptx - python

I know this module is not very popular but if you know the answer then please help me out with it.
My code is:
from pptx import Presentation
prs = Presentation('template.pptx')
title_slide_layout = prs.slide_layout[0]
# print(len(prs.slide_layout))
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
subtitle = slide.placeholders[1]
title.text = "Python 3.6 - Turtle Race"
subtitle.text = "Data Analytics&Visualization with random generated data"
prs.save("out.pptx")
An error I have got:
Traceback (most recent call last):
File "D:/!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton/turtleRace/presentationMaker.py", line 8, in <module>
prs = Presentation('template.pptx')
File "D:\!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton\turtleRace\venv\lib\site-packages\pptx\api.py", line 28, in Presentation
presentation_part = Package.open(pptx).main_document_part
File "D:\!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton\turtleRace\venv\lib\site-packages\pptx\opc\package.py", line 103, in main_document_part
return self.part_related_by(RT.OFFICE_DOCUMENT)
File "D:\!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton\turtleRace\venv\lib\site-packages\pptx\opc\package.py", line 136, in part_related_by
return self.rels.part_with_reltype(reltype)
File "D:\!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton\turtleRace\venv\lib\site-packages\pptx\opc\package.py", line 439, in part_with_reltype
rel = self._get_rel_of_type(reltype)
File "D:\!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton\turtleRace\venv\lib\site-packages\pptx\opc\package.py", line 491, in _get_rel_of_type
raise KeyError(tmpl % reltype)
KeyError: "no relationship of type 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument' in collection"
A picture of my project interpreter:
PICTURE
So why I have got this error?

It is an issue about the type when you save the file as Strict Open XML Presentation. Try the standard Presentation document.
You can get more informations about relations inside the file using opc-diag:
You can resolve error Here
Trying to fix a old file:
Extract
unzip <FILE> -d old-file
Repackage it into a new fresh file
opc repackage bad-file new-file.docx
diff of relationships
opc diff-item test.docx test-ok.docx .rels

I have found the solution!!!
Before I saved the file(called template) as Strict Open XML Presentation(.pptx)
and not as PowerPoint Presentation(.pptx)
It's now opening the file but now I have another error:
Traceback (most recent call last):
File "D:/!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!_!Piton/turtleRace/presentationMaker.py", line 9, in <module>
title_slide_layout = prs.slide_layout[0]
AttributeError: 'Presentation' object has no attribute 'slide_layout'
Everything is the same just the saving method in PowerPoint has changed.

Related

Python 3.9.9 Error " 'module' object is not a callable' - I am trying to download and extract .tgz file

I am trying to download and extract some data in .tgz file which I need to proceed with my book.
But unfortunately the code does not work.
I am receiving this error:
Traceback (most recent call last):
File "C:...\Python39_SciKit_&_TF_chapter2\main.py",
line 67, in <module>
fetch_housing_data()
File "C:...\Python39_SciKit_&_TF_chapter2\main.py",
line 54, in fetch_housing_data
with tarfile(FILE) as tar_data:
TypeError: 'module' object is not callable
And the code is:
# fetching data
URL = 'https://raw.githubusercontent.com/ageron/handson-ml2/master/datasets/housing/housing.tgz'
FILE = 'housing.tgz'
FOLDER = 'datasets'
def fetch_housing_data():
if not os.path.isfile(FILE):
print(f'Downloading {URL} and saving as {FILE}...')
urllib.request.urlretrieve(URL, FILE)
print('Unpacking file...')
with tarfile(FILE) as tar_data:
tar_data.extractall(FOLDER)
print('Tgz data has been extracted')
else:
print('The file is already in the folder')
And I don't know why this line gives an error:`
with tarfile(FILE) as tar_data:
tar_data.extractall(FOLDER)
Since I was using very similar approach with zip files and it worked.
Why python recognizes this as not collable and how do I make it work?

How to duplicate PowerPoint files in python?

Problem:
I'm trying to duplicate a slide from a presentation to another presentation, but it returns error:
Traceback (most recent call last):
File "C:\Users\vuse1\documents\visual studio 2015\Projects\PythonApplication\PythonApplication\PythonApplication.py", line 8, in
prs2.slides.add_slide(copySlide)
File "C:\Python27\lib\site-packages\pptx\slide.py", line 287, in add_slide
slide.shapes.clone_layout_placeholders(slide_layout)
File "C:\Python27\lib\site-packages\pptx\shapes\shapetree.py", line 515, in
clone_layout_placeholders for placeholder in slide_layout.iter_cloneable_placeholders():
AttributeError: 'Slide' object has no attribute 'iter_cloneable_placeholders'
Code:
from pptx import Presentation
prs1 = Presentation("C:\\Users\\vuse1\Desktop\\first.pptx")
prs2 = Presentation("C:\\Users\\vuse1\Desktop\\second.pptx")
copySlide=prs1.slides[0]
prs2.slides.add_slide(copySlide)
prs2.save("C:\\Users\\vuse1\Desktop\\second.pptx")
Copying slides isn't officially supported by the library. There's a lot of discussion about this topic. Look at this github issue for workarounds.

Unable to generate PDF with wkhtmltopdf on a headless server

I have a HTML document that uses CSS files and a around a dozen PNG files generated out of matplotlib. To convert this HTML document into a PDF, I installed wkhtmltopdf, on a AWS EC2 Linux instance, in a manner described here.
On the command line, this works
wkhtmltopdf http://www.google.com output.pdf
However, the following Python snippet does not work.
reportCss = pathlib.Path(os.path.join(cssDir, 'report.css'))
w3Css = pathlib.Path(os.path.join(cssDir, 'w3.css'))
#
options = {
'page-size': 'A4',
'dpi': 720,
'margin-bottom': 5
}
css = [str(reportCss), str(w3Css)]
pdfkit.from_file(htmlFilePath, pdfFilePath, options=options, css=css)
I get this error:
QPainter::begin(): Returned false
Traceback (most recent call last):
File "dailyemail.py", line 55, in <module>
main()
File "dailyemail.py", line 44, in main
pdfFileName = pdfgen.buildPdfDoc()
File "/home/ubuntu/demo/py/pdfgen.py", line 58, in buildPdfDoc
pdfkit.from_file(htmlFilePath, pdfFilePath, options=options, css=css)
File "/home/ubuntu/.local/lib/python2.7/site-packages/pdfkit/api.py", line 49, in from_file
return r.to_pdf(output_path)
File "/home/ubuntu/.local/lib/python2.7/site-packages/pdfkit/pdfkit.py", line 181, in to_pdf
'%s ' %(' '.join(args)),e)
TypeError: not enough arguments for format string
Can you please advise what am I missing?
Turned out that the PDF folder wasn't existing. The error message is mid leading.

Can't run simple python reddit program?

Here is the python reddit program, the code is 100% fine. It's from a tutorial website.
#!/usr/bin/python
import praw
reddit = praw.Reddit('bot1')
subreddit = reddit.subreddit("learnpython")
for submission in subreddit.hot(limit=5):
print("Title: ", submission.title)
print("Text: ", submission.selftext)
print("Score: ", submission.score)
print("---------------------------------\n")
When I run it I get this error.
Traceback (most recent call last):
File "Top3Links.py", line 4, in <module>
reddit = praw.Reddit('bot1')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
packages/praw/reddit.py", line 105, in __init__
**config_settings)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-
packages/praw/config.py", line 64, in __init__
self.custom = dict(Config.CONFIG.items(site_name), **settings)
File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ConfigParser.py", line 347, in items
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'bot1'
Eric-MacBook-Pro:PythonRedditBot Eric$
It maybe has something to do with installing python 3.5 any help would be amazing.
You appear to be missing a config file for this module. Check out the documentation:
https://praw.readthedocs.io/en/latest/getting_started/configuration/prawini.html
According to the documentation, you need a praw.ini file, containing a section like this:
[bot1]
client_id=Y4PJOclpDQy3xZ
client_secret=UkGLTe6oqsMk5nHCJTHLrwgvHpr
password=pni9ubeht4wd50gk
username=fakebot1
The source may also be informative: https://github.com/praw-dev/praw/blob/master/praw/reddit.py#L79

ImportError: No module named __main__ (Python 2.7 & Pickle)

So on my game I'm making, I'm trying to load the data files needed for the game, and when I load the file with pickle (The file has been loaded, I've double-checked that.) I get this error:
Traceback (most recent call last):
File "/Users/user/Downloads/Deeper-master/Deeper.py", line 257, in <module>
tutorialData = pickle.load(tutorialFile)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1384, in load
return Unpickler(file).load()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 864, in load
dispatch[key](self)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1075, in load_inst
klass = self.find_class(module, name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1130, in find_class
__import__(module)
ImportError: No module named __main__
I saw a question like this on Stack Overflow, but it's a little different than my situation, so sorry if this is a duplicate, I'm just trying to figure it out.
You can find my code here. The main script is Deeper.py, just to save time.
If you notice in your repo, you have a Deeper.pyc and Deeper.py. If I run Deeper.py, it raises the same exception as yours. If I run Deeper.pyc, it raises another exception:
Traceback (most recent call last):
File "Deeper.py", line 7, in <module>
ToolbarTile = pygame.image.load("ToolbarTile.png")
pygame.error: Couldn't open Toolbar Tile.png
So, the code (bytecode, some previous version) references ToolbarTile.png, but the exception is about Toolbar Tile.png (with a space). So I changed the file name to account for that.
Now it raises:
Traceback (most recent call last):
File "Deeper.py", line 766, in <module>
else:
File "Deeper.py", line 394, in __init__
def displayCraft(self):
pygame.error: Couldn't open options.png
There's an Options.png in your files, but it looks for options.png (lower case) (even your new code in Deeper.py looks for that). So I changed that.
Now it works, albeit with Deeper.pyc so that must be why you thought:
(The file has been loaded, I've double-checked that.)
Maybe delete the Deeper.pyc and do a git-bisect to see when the bug was introduced (ps: check your toolbar.dat, does it seem okay to you? Also check the way you're using pickle.load. Maybe you should use rb instead of r?)

Categories

Resources