<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Kat McKelvie, Author at Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/author/katmckelvie/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/author/katmckelvie/</link>
	<description></description>
	<lastBuildDate>Thu, 23 Feb 2023 18:28:47 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Kat McKelvie, Author at Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/author/katmckelvie/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>5 Easy Ways to Download an Image from a URL in Python</title>
		<link>https://blog.finxter.com/5-easy-ways-to-download-an-image-from-a-url-in-python/</link>
		
		<dc:creator><![CDATA[Kat McKelvie]]></dc:creator>
		<pubDate>Wed, 22 Feb 2023 08:28:57 +0000</pubDate>
				<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Image Processing]]></category>
		<category><![CDATA[Pillow]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Web Scraping]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=322918</guid>

					<description><![CDATA[<p>Problem Formulation and Solution Overview In this article, you&#8217;ll learn how to download an image from the web in Python. To make it more fun, we have the following running scenario: Sven, a Journalist from Greeland, is writing about Glacier Calving. His editor would like photos of iceberg collapses in the area accompanying his article. ... <a title="5 Easy Ways to Download an Image from a URL in Python" class="read-more" href="https://blog.finxter.com/5-easy-ways-to-download-an-image-from-a-url-in-python/" aria-label="Read more about 5 Easy Ways to Download an Image from a URL in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/5-easy-ways-to-download-an-image-from-a-url-in-python/">5 Easy Ways to Download an Image from a URL in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-heading">Problem Formulation and Solution Overview</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="694" height="458" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-326.png" alt="" class="wp-image-1156817" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-326.png 694w, https://blog.finxter.com/wp-content/uploads/2023/02/image-326-300x198.png 300w" sizes="(max-width: 694px) 100vw, 694px" /></figure>
</div>


<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">In this article, you&#8217;ll learn how to download an image from the web in Python. </p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">To make it more fun, we have the following running scenario:</p>



<p><em><strong>Sven</strong>, a Journalist from Greeland, is writing about <a rel="noreferrer noopener" href="https://www.youtube.com/watch?v=49bYTMo3Vxw" data-type="URL" data-id="https://www.youtube.com/watch?v=49bYTMo3Vxw" target="_blank">Glacier </a><a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Ice_calving" data-type="URL" data-id="https://en.wikipedia.org/wiki/Ice_calving" target="_blank">Calving</a>. His editor would like photos of iceberg collapses in the area accompanying his article. Unfortunately, <strong>Sven</strong> is not tech-savvy and needs your help. </em></p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4ac.png" alt="💬" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write Python code to perform image downloads?</p>



<p>We can accomplish this task by one of the following options:</p>



<ul class="wp-block-list">
<li><strong>Method 1</strong>: Use <code><a href="https://blog.finxter.com/python-requests-library-2/" data-type="URL" data-id="https://blog.finxter.com/python-requests-library-2/" target="_blank" rel="noreferrer noopener">requests.get()</a></code> and <code>write()</code></li>



<li><strong>Method 2</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library-2/" data-type="URL" data-id="https://blog.finxter.com/python-requests-library-2/" target="_blank"><code>requests.get()</code></a> and <a href="https://pillow.readthedocs.io/en/stable/" data-type="URL" data-id="https://pillow.readthedocs.io/en/stable/" target="_blank" rel="noreferrer noopener"><code>Image</code></a></li>



<li><strong>Method 3</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library-2/" data-type="URL" data-id="https://blog.finxter.com/python-requests-library-2/" target="_blank"><code>requests.get()</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-shutil-high-level-file-operations-demystified/" data-type="URL" data-id="https://blog.finxter.com/python-shutil-high-level-file-operations-demystified/" target="_blank"><code>shutil</code></a></li>



<li><strong>Method 4</strong>: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/urllib.html" data-type="URL" data-id="https://docs.python.org/3/library/urllib.html" target="_blank"><code>urllib.request.urlretrieve()</code></a></li>



<li><strong>Bonus: </strong>Download all images using a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank">For</a> loop</li>
</ul>



<h2 class="wp-block-heading">Quick Solution</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="513" height="766" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-327.png" alt="" class="wp-image-1156818" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-327.png 513w, https://blog.finxter.com/wp-content/uploads/2023/02/image-327-201x300.png 201w" sizes="(max-width: 513px) 100vw, 513px" /></figure>
</div>


<p>Short on time? Here&#8217;s a one-paragraph answer:</p>



<p class="has-global-color-8-background-color has-background">To download an image in Python, import the <code>requests</code> library and pass the URL of the image into the <code>requests.get(url)</code> function to get a response object from the server. Its <code>response.content</code> attribute gets you the binary image content. Finally, use the <code>open()</code> and <code>write()</code> functions to write the binary content to a new file.</p>



<p>Here&#8217;s the quick code solution:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests

url = "https://example.com/image.jpg"
response = requests.get(url)

with open("image.jpg", "wb") as f:
    f.write(response.content)</pre>



<h2 class="wp-block-heading">Preparation and Library Installation</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="510" height="500" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-328.png" alt="" class="wp-image-1156831" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-328.png 510w, https://blog.finxter.com/wp-content/uploads/2023/02/image-328-300x294.png 300w" sizes="(max-width: 510px) 100vw, 510px" /></figure>
</div>


<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Before our code executes successfully, two (2) new libraries will require installation.</p>



<ul class="wp-block-list">
<li>The <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library/" data-type="URL" data-id="https://blog.finxter.com/python-requests-library/" target="_blank"><code>requests</code></a> library is used to send and receive HTTP requests.</li>



<li>The <code><a href="https://pillow.readthedocs.io/en/stable/" data-type="URL" data-id="https://pillow.readthedocs.io/en/stable/">pillow</a> </code>(<code>PIL</code>) library is used to retrieve and process images.</li>
</ul>



<p>To install these libraries, navigate to an <a rel="noreferrer noopener" href="https://blog.finxter.com/best-python-ide/" data-type="post" data-id="8106" target="_blank">IDE</a> terminal. At the command prompt (<code>$</code>), execute the code below. For the terminal used in this example, the command prompt is a dollar sign (<code>$</code>). Your terminal prompt may be different.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ pip install requests</pre>



<p>Hit the <code>&lt;Enter&gt;</code> key on the keyboard to start the installation process.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ pip install pillow</pre>



<p>Hit the <code>&lt;Enter&gt;</code> key on the keyboard to start the installation process.</p>



<p>If the installations were successful, a message displays in the terminal indicating the same.</p>



<hr class="wp-block-separator has-css-opacity"/>



<p>Feel free to view the PyCharm installation guide for the required libraries.</p>



<ul class="wp-block-list">
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-a-library-on-pycharm/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-a-library-on-pycharm/" target="_blank">How to install Requests on PyCharm</a></li>



<li><a href="https://blog.finxter.com/how-to-install-pillow-on-pycharm/#:~:text=Select%20your%20current%20project.,quotes%2C%20and%20click%20Install%20Package%20." data-type="URL" data-id="https://blog.finxter.com/how-to-install-pillow-on-pycharm/#:~:text=Select%20your%20current%20project.,quotes%2C%20and%20click%20Install%20Package%20." target="_blank" rel="noreferrer noopener">How to install Pillow on PyCharm</a></li>
</ul>



<p>Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests
from PIL import Image
import shutil
import urllib</pre>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" />&nbsp;<strong>Note</strong>: The additional libraries indicated above do not require installation as they come built-in to Python.</p>



<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Method 1: Use requests.get() and write()</h2>



<p class="has-global-color-8-background-color has-background">The <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library-2/" data-type="URL" data-id="https://blog.finxter.com/python-requests-library-2/" target="_blank"><code>requests.get()</code></a> function is used with file <a rel="noreferrer noopener" href="https://blog.finxter.com/python-open-function/" data-type="URL" data-id="https://blog.finxter.com/python-open-function/" target="_blank"><code>open()</code></a> and <a rel="noreferrer noopener" href="https://python-reference.readthedocs.io/en/latest/docs/file/write.html" data-type="URL" data-id="https://python-reference.readthedocs.io/en/latest/docs/file/write.html" target="_blank"><code>write()</code></a> to download and save the specified file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2,4-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">img_url = 'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_01a.jpg'
response = requests.get(img_url)
if response.status_code:
    fp = open('greenland_01a.png', 'wb')
    fp.write(response.content)
    fp.close()</pre>



<p>The above code attempts to connect to the stated URL (<code>img_url</code>). If successful, a <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#1xx_informational_response" data-type="URL" data-id="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#1xx_informational_response" target="_blank">Status Code</a> of 200 is returned. This image is then opened and written to the specified file and saved to the current working directory.</p>



<p><strong>Output</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2022/04/greenland_01a.jpg" alt="" class="wp-image-326882" width="700" height="394" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/greenland_01a.jpg 640w, https://blog.finxter.com/wp-content/uploads/2022/04/greenland_01a-300x169.jpg 300w" sizes="auto, (max-width: 700px) 100vw, 700px" /></figure>
</div>


<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Method 2: Use requests.get() and Image()</h2>



<p class="has-global-color-8-background-color has-background">The <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library-2/" data-type="URL" data-id="https://blog.finxter.com/python-requests-library-2/" target="_blank"><code>requests</code></a> library is used with the <a rel="noreferrer noopener" href="https://pillow.readthedocs.io/en/stable/" data-type="URL" data-id="https://pillow.readthedocs.io/en/stable/" target="_blank"><code>PIL</code></a> library&#8217;s <code>open()</code> and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library-2/" data-type="URL" data-id="https://blog.finxter.com/python-requests-library-2/" target="_blank"><code>requests.get()</code></a> functions to download and save the specified file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">img_url = 'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_02a.jpg'
img = Image.open(requests.get(img_url, stream = True).raw)
img.save('greenland_02a.png')</pre>



<p>The above code connects to the stated URL (<code>img_url</code>). This image is then opened and written in raw format to <code>img</code>. Finally, it is saved to the current working directory as an image file.</p>



<p><strong>Output</strong>:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2022/04/greenland_02a.jpg" alt="" class="wp-image-326889" width="699" height="393" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/greenland_02a.jpg 640w, https://blog.finxter.com/wp-content/uploads/2022/04/greenland_02a-300x169.jpg 300w" sizes="auto, (max-width: 699px) 100vw, 699px" /></figure>
</div>


<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Method 3: Use requests.get() and shutil</h2>



<p class="has-global-color-8-background-color has-background">The <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library-2/" data-type="URL" data-id="https://blog.finxter.com/python-requests-library-2/" target="_blank"><code>requests</code></a> library is used with the <a rel="noreferrer noopener" href="https://pillow.readthedocs.io/en/stable/" data-type="URL" data-id="https://pillow.readthedocs.io/en/stable/" target="_blank"></a><a rel="noreferrer noopener" href="https://blog.finxter.com/python-shutil-high-level-file-operations-demystified/" data-type="URL" data-id="https://blog.finxter.com/python-shutil-high-level-file-operations-demystified/" target="_blank"><code>shutil</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library-2/" data-type="URL" data-id="https://blog.finxter.com/python-requests-library-2/" target="_blank"><code>requests.get()</code></a> functions to copy, download and save the specified file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2,5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">img_url = 'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_03a.jpg'
response = requests.get(img_url, stream=True)
with open('greenland_03a.png', 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file)
del response</pre>



<p>This code retrieves the specified URL, then opens and creates a file object. This object saves the file stated in <code>open()</code> to the current working directory. To clean up, the response object is removed.</p>



<p><strong>Output</strong></p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2022/04/greenland_03a.jpg" alt="" class="wp-image-326891" width="700" height="394" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/greenland_03a.jpg 640w, https://blog.finxter.com/wp-content/uploads/2022/04/greenland_03a-300x169.jpg 300w" sizes="auto, (max-width: 700px) 100vw, 700px" /></figure>
</div>


<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Method 4: Use urllib.request.urlretrieve()</h2>



<p class="has-global-color-8-background-color has-background">This code uses the <code>urllib</code> and <code>requests</code> libraries to connect, retrieve, process, and save the image. For example, we call <code>urllib.request.urlretrieve(img_url, "greenland_04a.png")</code> to download the image at the given URL.</p>



<p>Here&#8217;s the full example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">img_url = 'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_04a.jpg'
urllib.request.urlretrieve(img_url, "greenland_04a.png")</pre>



<p>On one line of code, this code calls the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library/" data-type="URL" data-id="https://blog.finxter.com/python-requests-library/" target="_blank"><code>requests</code></a> and <a href="https://docs.python.org/3/library/urllib.html" data-type="URL" data-id="https://docs.python.org/3/library/urllib.html" target="_blank" rel="noreferrer noopener"><code>urllib</code></a> libraries to perform all the tasks to retrieve, process, and save the indicated image to the current working directory.</p>



<p><strong>Output</strong></p>



<figure class="wp-block-image size-full is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2022/04/greenland_04a.jpg" alt="" class="wp-image-326895" width="698" height="478" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/greenland_04a.jpg 640w, https://blog.finxter.com/wp-content/uploads/2022/04/greenland_04a-300x205.jpg 300w" sizes="auto, (max-width: 698px) 100vw, 698px" /></figure>



<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Bonus:</h2>



<p class="has-global-color-8-background-color has-background">This code grabs all the URLs above and pastes them to a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">list</a>. Next, the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">list</a> is referenced in a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> loop. Finally, each image is retrieved, processed, and saved to the current working directory.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="11" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import urllib
import requests

imgs = ['https://blog.finxter.com/wp-content/uploads/2022/04/greenland_01a.jpg',
        'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_02a.jpg',
        'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_03a.jpg',
        'https://blog.finxter.com/wp-content/uploads/2022/04/greenland_04a.jpg']

icount=1
for i in imgs:
    urllib.request.urlretrieve(i, f'greenland_0{str(icount)}b.png')
    icount += 1</pre>



<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Thanks <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2665.png" alt="♥" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>



<p>These four (4) methods of downloading and saving images should give you enough information to select the best one for your coding requirements.</p>



<p>Feel free to check out our free email academy here:</p>






<p>Good Luck &amp; Happy Coding!</p>



<hr class="wp-block-separator has-css-opacity"/>



<p><a href="https://pixabay.com/images/search/iceberg%20greenland/" data-type="URL" data-id="https://pixabay.com/images/search/iceberg%20greenland/" target="_blank" rel="noreferrer noopener">Image Sources.</a></p>
<p>The post <a href="https://blog.finxter.com/5-easy-ways-to-download-an-image-from-a-url-in-python/">5 Easy Ways to Download an Image from a URL in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Setup a Virtual Environment with Visual Studio Code in Python</title>
		<link>https://blog.finxter.com/setup-a-virtual-environment-with-visual-studio-code-in-python/</link>
		
		<dc:creator><![CDATA[Kat McKelvie]]></dc:creator>
		<pubDate>Wed, 30 Nov 2022 14:29:32 +0000</pubDate>
				<category><![CDATA[Dependency Management]]></category>
		<category><![CDATA[pip]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=935562</guid>

					<description><![CDATA[<p>Problem Formulation and Solution Overview This article will show you how to create a Virtual Environment inside the Visual Studio Code, the VSC Editor. Virtual Environments are best used when a coder or several coders work together to develop medium to large-scale applications. The best approach is to keep this code and associated libraries and ... <a title="Setup a Virtual Environment with Visual Studio Code in Python" class="read-more" href="https://blog.finxter.com/setup-a-virtual-environment-with-visual-studio-code-in-python/" aria-label="Read more about Setup a Virtual Environment with Visual Studio Code in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/setup-a-virtual-environment-with-visual-studio-code-in-python/">Setup a Virtual Environment with Visual Studio Code in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-heading">Problem Formulation and Solution Overview</h2>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">This article will show you how to create a <a href="https://blog.finxter.com/python-virtual-environments-with-venv-a-step-by-step-guide/" data-type="post" data-id="3393" target="_blank" rel="noreferrer noopener">Virtual Environment</a> inside the Visual Studio Code, the VSC Editor.</p>



<p>Virtual Environments are best used when a coder or several coders work together to develop medium to large-scale applications. The best approach is to keep this code and associated libraries and dependencies separate. This is where a Virtual Environment comes in!</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Setting up the Environment</h2>



<p>Open the Visual Studio Code Editor and create a new folder that will house the Python script to be worked on.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="413" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_001-1024x413.png" alt="" class="wp-image-935712" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_001-1024x413.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_001-300x121.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_001-768x310.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_001.png 1147w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Create a blank script file called <code>sales.py</code> and place this file into this directory.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="415" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_002-1024x415.png" alt="" class="wp-image-935742" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_002-1024x415.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_002-300x122.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_002-768x311.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_002.png 1137w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>From the View menu, select Command Pallette or press <code>CTRL+SHIFT+P</code> on the keyboard for the same result.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="417" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_003-1024x417.png" alt="" class="wp-image-935800" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_003-1024x417.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_003-300x122.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_003-768x312.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_003.png 1143w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>The above action displays a dropdown box. Start typing the word <em>Python: Create Environment</em>, or if visible, click to select this option.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="420" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_005-1024x420.png" alt="" class="wp-image-935810" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_005-1024x420.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_005-300x123.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_005-768x315.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_005.png 1134w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>The above action displays another dropdown box. For this article, the first option was selected (<code><a href="https://blog.finxter.com/python-virtual-environments-with-venv-a-step-by-step-guide/" data-type="post" data-id="3393" target="_blank" rel="noreferrer noopener">Venv</a></code>).</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="417" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_006-1024x417.png" alt="" class="wp-image-935821" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_006-1024x417.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_006-300x122.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_006-768x313.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_006.png 1141w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>The above action displays another dropdown box. For this article, the second option was selected (<code>Python 3.11.0 64-bit</code>).</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="418" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_007-1024x418.png" alt="" class="wp-image-935862" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_007-1024x418.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_007-300x122.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_007-768x314.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_007.png 1144w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>The above action starts the installation of the Virtual Environment. Wait for this process to complete.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="415" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_008-1024x415.png" alt="" class="wp-image-935874" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_008-1024x415.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_008-300x122.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_008-768x311.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_008.png 1147w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Once the Virtual Environment is installed, the following occurs:</p>



<ul class="wp-block-list">
<li>A message in the status bar indicates the name of the Virtual Environment (<code>.venv:env</code>)</li>



<li>A new folder called <code>.venv</code> is created.</li>
</ul>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="416" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_009-1024x416.png" alt="" class="wp-image-935897" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_009-1024x416.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_009-300x122.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_009-768x312.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM_ENV_009.png 1145w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Next, locate and open the <code>activate.bat</code> from the <code>.venv\Scripts</code> folder. From the Main Menu, Click <code>Run → Start Debugging</code> or press <code>F5</code> on the keyboard.</p>



<p>If successful, the command prompt changes similar to below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="471" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-23-1024x471.png" alt="" class="wp-image-936361" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-23-1024x471.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-23-300x138.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-23-768x354.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-23.png 1401w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>You are now officially working in a Virtual Environment.</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Note</strong>: If an error is generated when running this <code>.bat</code> file, you may need to install an extension that reads <a href="https://blog.finxter.com/how-to-schedule-a-batch-python-script/" data-type="post" data-id="880057" target="_blank" rel="noreferrer noopener">Batch files</a>. For this article, Batch Runner was installed.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Install Required Library</h2>



<p>For this article, our <code>sales.py</code> file reads in the <a rel="noreferrer noopener" href="https://blog.finxter.com/wp-content/uploads/2022/11/sales.csv" data-type="URL" data-id="https://blog.finxter.com/wp-content/uploads/2022/11/sales.csv" target="_blank"><code>sales.csv</code></a> file. This means that the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="URL" data-id="https://blog.finxter.com/pandas-quickstart/" target="_blank">pandas</a></code> library will need to be installed. To perform this task, navigate to the terminal window and run the following code.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install pandas</pre>



<p>If successful, the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="URL" data-id="https://blog.finxter.com/pandas-quickstart/" target="_blank">pandas</a></code> library is now installed in the Virtual Environment and if we run <code>sales.py</code> there should be no errors.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="453" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-24-1024x453.png" alt="" class="wp-image-936410" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-24-1024x453.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-24-300x133.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-24-768x340.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-24.png 1462w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class="has-global-color-8-background-color has-background"><strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Note</strong>: Install any other required libraries the same way.</p>



<ul class="wp-block-list">
<li><a href="https://blog.finxter.com/how-to-install-xxx-in-python/" data-type="post" data-id="653128" target="_blank" rel="noreferrer noopener">How to Install a Python Library</a></li>



<li><a href="https://blog.finxter.com/how-to-install-pandas-in-python/" data-type="post" data-id="35926" target="_blank" rel="noreferrer noopener">How to Install Pandas?</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Generate a Requirements File</h2>



<p>A <strong>Requirements File</strong> can be created at any time during the development cycle. This file is a checklist for the Python application in question. It lists all libraries and associated versions used in the app.</p>



<p>To generate a <code>requirements.txt</code> file, navigate to the terminal and run the following code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip freeze > requirements.txt</pre>



<p>This action generates the above-noted file and places it into, for this example, the <code>SALES_APP</code> folder. Open this file and scroll down to see the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="URL" data-id="https://blog.finxter.com/pandas-quickstart/" target="_blank">pandas</a></code> library listed, including the version number. This is handy when deploying to another Virtual Environment to ensure the correct library versions are installed.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Deactivating the Virtual Environment</h2>



<p>To deactivate the Virtual Environment, click the (<code>.venv:env</code>) link in the bottom-right of the IDE. This action displays the Interpreter dropdown box. Select <code>Python 3.11.0 64-bit</code> or any other option that does not contain the <code>(.venv:env</code>) words.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="448" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-27-1024x448.png" alt="" class="wp-image-936693" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-27-1024x448.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-27-300x131.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-27-768x336.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-27.png 1464w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>If successful, the status bar no longer has the (.venv:env) link, and the prompt no longer contains that as well.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="454" src="https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-26-1024x454.png" alt="" class="wp-image-936571" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-26-1024x454.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-26-300x133.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-26-768x341.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/KM-VENV-26.png 1461w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>While still in the Virtual Environment, another option is to navigate to the Scripts folder, open and run <code>deactivate.bat</code> file</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Summary</h2>



<p>This article showed you how to setup, activate, and de-activate a Virtual Environment in the VS Code IDE.</p>



<p>The post <a href="https://blog.finxter.com/setup-a-virtual-environment-with-visual-studio-code-in-python/">Setup a Virtual Environment with Visual Studio Code in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Generate a Simple PDF using Python ReportLab (9 Steps)</title>
		<link>https://blog.finxter.com/generate-a-simple-pdf-using-python-reportlab-9-steps/</link>
		
		<dc:creator><![CDATA[Kat McKelvie]]></dc:creator>
		<pubDate>Mon, 28 Nov 2022 15:14:26 +0000</pubDate>
				<category><![CDATA[Data Conversion]]></category>
		<category><![CDATA[Input/Output]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=926731</guid>

					<description><![CDATA[<p>Problem Formulation and Solution Overview This article shows how to generate a formatted PDF file from a CSV file using the ReportLab and Pandas libraries in conjunction with slicing. ℹ️ Python offers numerous ways to generate a PDF file. One option is to use the ReportLab library. The article selected the path that used the ... <a title="Generate a Simple PDF using Python ReportLab (9 Steps)" class="read-more" href="https://blog.finxter.com/generate-a-simple-pdf-using-python-reportlab-9-steps/" aria-label="Read more about Generate a Simple PDF using Python ReportLab (9 Steps)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/generate-a-simple-pdf-using-python-reportlab-9-steps/">Generate a Simple PDF using Python ReportLab (9 Steps)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-heading">Problem Formulation and Solution Overview</h2>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">This article shows how to generate a formatted PDF file from a CSV file using the <a rel="noreferrer noopener" href="https://docs.reportlab.com/" data-type="URL" data-id="https://docs.reportlab.com/" target="_blank"></a><code><code><a rel="noreferrer noopener" href="https://pypi.org/project/reportlab/" data-type="URL" data-id="https://pypi.org/project/reportlab/" target="_blank">ReportLab</a></code> </code>and <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-pandas-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-pandas-in-python/" target="_blank"><code>Pandas</code></a> libraries in conjunction with <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank"><code>slicing</code></a>.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Python offers numerous ways to generate a PDF file. One option is to use the <code><a rel="noreferrer noopener" href="https://pypi.org/project/reportlab/" data-type="URL" data-id="https://pypi.org/project/reportlab/" target="_blank">ReportLab</a></code> library. The article selected the path that used the least amount of code.</p>



<p>To make it more interesting, we have the following running scenario:</p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f697.png" alt="🚗" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Example Scenario</strong>: <em><a rel="noreferrer noopener" href="https://blog.finxter.com/wp-admin/post.php?post=917299&amp;action=edit" data-type="URL" data-id="https://blog.finxter.com/wp-admin/post.php?post=917299&amp;action=edit" target="_blank">KarTek</a>, a car dealership in Toronto, previously asked you to import their CSV file into a Database. They would like this data converted to a PDF format to email out to their Sales Staff</em> <em>daily</em>.</p>



<p>To follow along with this article, <a rel="noreferrer noopener" href="https://blog.finxter.com/wp-content/uploads/2022/11/cars.csv" data-type="URL" data-id="https://blog.finxter.com/wp-content/uploads/2022/11/cars.csv" target="_blank">download</a> and place the <code>cars.csv</code> file into the current working directory:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://blog.finxter.com/wp-content/uploads/2022/11/cars.csv" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="933" height="832" src="https://blog.finxter.com/wp-content/uploads/2022/11/image-267.png" alt="" class="wp-image-921281" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/image-267.png 933w, https://blog.finxter.com/wp-content/uploads/2022/11/image-267-300x268.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/image-267-768x685.png 768w" sizes="auto, (max-width: 933px) 100vw, 933px" /></a></figure>
</div>


<p>Download and save the logo file to the current working directory as car_logo.png.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="170" height="52" src="https://blog.finxter.com/wp-content/uploads/2022/11/car_logo.png" alt="" class="wp-image-928898" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio" />



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4ac.png" alt="💬" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write code to generate a PDF from a CSV file<em>?</em></p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can create a PDF from a CSV file by performing the following steps:</p>



<ol class="wp-block-list" type="video">
<li><strong>Install </strong><code><strong><code><code><a rel="noreferrer noopener" href="https://pypi.org/project/reportlab/" data-type="URL" data-id="https://pypi.org/project/reportlab/" target="_blank">ReportLab</a></code></code></strong> <strong>and <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-pandas-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-pandas-in-python/" target="_blank"><code>Pandas</code></a></strong></code> <strong>Libraries</strong></li>



<li><strong>Add Library References </strong></li>



<li><strong>Read CSV File</strong></li>



<li><strong>Calculate Total Pages</strong></li>



<li><strong>Get Stylesheet and Template</strong></li>



<li><strong>Create Page Header</strong></li>



<li><strong>Paginate the Data</strong></li>



<li><strong>Build the PDF</strong></li>



<li><strong>Generate the PDF</strong></li>
</ol>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Step 1: Install ReportLab and Pandas Libraries</h2>



<p class="has-global-color-8-background-color has-background">Before moving forward, the <code><code><a rel="noreferrer noopener" href="https://pypi.org/project/reportlab/" data-type="URL" data-id="https://pypi.org/project/reportlab/" target="_blank">ReportLab</a></code></code> and <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-pandas-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-pandas-in-python/" target="_blank"><code>Pandas</code></a> libraries must be installed. To install these libraries, run the following code at the command prompt.</p>



<p>The <code><code><a rel="noreferrer noopener" href="https://pypi.org/project/reportlab/" data-type="URL" data-id="https://pypi.org/project/reportlab/" target="_blank">ReportLab</a></code></code> library is needed to generate a PDF, and the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-pandas-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-pandas-in-python/" target="_blank"><code>Pandas</code></a> library is required to read and manipulate the <code>cars.csv</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install reportlab
pip install pandas</pre>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Step 2: Add Library References</h2>



<p class="has-global-color-8-background-color has-background">To run this code error-free, references to the required modules must be added.</p>



<p>To add these references, navigate to the IDE. Create a file called <code>pdf.py</code> and place this file into the current working directory.</p>



<p>Copy the code snippet below and paste this code into the above-created file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from reportlab.platypus import *
from reportlab.lib.styles import *
from reportlab.lib import *
from reportlab.platypus import *
import pandas as pd
import math </pre>



<p>An alternate option would be to reference precisely what is needed.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import PageBreak
from reportlab.platypus import SimpleDocTemplate, Table, PageBreak, Image, Paragraph, Spacer
from reportlab.lib import colors
import pandas as pd
import math </pre>



<p>The first option is much cleaner. There are pros and cons for each selection. However, the choice is up to you.</p>



<p>Save this file.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Step 3: Read CSV File</h2>



<p class="has-global-color-8-background-color has-background">The next step is to <a rel="noreferrer noopener" href="https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/" data-type="post" data-id="440655" target="_blank">read the CSV</a> file and extract the heading row.</p>



<p>Copy and paste this code snippet to the bottom of the <code>pdf.py</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df_cars = pd.read_csv('cars.csv', sep=';').head(60)
df_data = [df_cars.columns[:,].values.astype(str).tolist()] + df_cars.values.tolist()
pg_data = df_data[1:]</pre>



<p>The first line in the above code snippet reads in the first 60 rows (<a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-dataframe-head-method/" data-type="URL" data-id="https://blog.finxter.com/pandas-dataframe-head-method/" target="_blank"><code>head(60)</code></a>) of the <code>cars.csv</code> file. In this file, the field separator character is a semi-colon (<code>;)</code> and must be specified, as <code><a rel="noreferrer noopener" href="https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/" data-type="URL" data-id="https://blog.finxter.com/read-a-csv-file-to-a-pandas-dataframe/" target="_blank">read_csv()</a></code> assumes the separator character is a comma (<code>,</code>). The results save to <code>df_cars</code>.</p>



<p>The following line casts all data types to strings <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-check-data-type-of-a-panda-series/" data-type="URL" data-id="https://blog.finxter.com/how-to-check-data-type-of-a-panda-series/" target="_blank"><code>astype(str)</code></a> and splits the data into <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>lists</code></a>. The result saves to <code>df_data</code>. If output to the terminal, the data would display as shown below (a snippet of the file).</p>



<pre class="wp-block-preformatted"><code>[<strong>['Car', 'MPG', 'Cylinders', 'Displacement', 'Horsepower', 'Weight', 'Acceleration', 'Model', 'Origin']</strong>, </code>
 <code>['Chevrolet Chevelle Malibu', 18.0, 8, 307.0, 130.0, 3504.0, 12.0, 70, 'US'], </code>
 <code>['Buick Skylark 320', 15.0, 8, 350.0, 165.0, 3693.0, 11.5, 70, 'US'], </code>
 <code>['Plymouth Satellite', 18.0, 8, 318.0, 150.0, 3436.0, 11.0, 70, 'US'], ...]</code></pre>



<p>The last line removes the header row using <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank" rel="noreferrer noopener"><code>slicing</code></a>, leaving only the data. The results save to <code>pg_data</code>. If output to the terminal, the data would display as shown below (a snippet of the file).</p>



<pre class="wp-block-preformatted"><code>[['Chevrolet Chevelle Malibu', 18.0, 8, 307.0, 130.0, 3504.0, 12.0, 70, 'US'], ['Buick Skylark 320', 15.0, 8, 350.0, 165.0, 3693.0, 11.5, 70, 'US'], ['Plymouth Satellite', 18.0, 8, 318.0, 150.0, 3436.0, 11.0, 70, 'US'], ['AMC Rebel SST', 16.0, 8, 304.0, 150.0, 3433.0, 12.0, 70, 'US'], ...]</code></pre>



<p>Save this file.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python List Methods" width="937" height="527" src="https://www.youtube.com/embed/4j8B9a_kZY4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Step 4: Calculate Total Pages</h2>



<p class="has-global-color-8-background-color has-background">This code snippet is used to calculate how many pages the PDF will be.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">elements = []
recs_pg = 39
tot_pgs = math.ceil(len(df_data) / recs_pg)</pre>



<p>The first line in the above code snippet declares an empty <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a> called <code>elements</code>. This <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a> will hold all the page formatting for the PDF.</p>



<p>The following line declares how many records per page will display (not including the header row). The results save to <code>recs_pg</code>.</p>



<p>The last line uses the <a href="https://blog.finxter.com/python-math-functions/" data-type="URL" data-id="https://blog.finxter.com/python-math-functions/" target="_blank" rel="noreferrer noopener"><code>ceil()</code></a> function from the <a href="https://blog.finxter.com/python-math-functions/" data-type="URL" data-id="https://blog.finxter.com/python-math-functions/" target="_blank" rel="noreferrer noopener"><code>math</code></a> library to calculate how many pages this PDF will be. This function returns an integer value. The results save to <code>tot_pgs</code>. If output to the terminal, the following will display.</p>



<pre class="wp-block-preformatted"><code>2</code></pre>



<p>Save this file.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Math Module [Ultimate Guide]" width="937" height="703" src="https://www.youtube.com/embed/F_4XbBVlXDg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Step 5: Get Stylesheet and Template</h2>



<p class="has-global-color-8-background-color has-background">This code snippet is used to set the styles and a template for the PDF.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">styles = getSampleStyleSheet()
doc = SimpleDocTemplate('inventory.pdf', rightMargin=0, leftMargin=0, topMargin=0, bottomMargin=0)</pre>



<p>The first line in the above code snippet gets the <a rel="noreferrer noopener" href="https://pyng.tech/docs/reportlab/lib/styles.m.html" data-type="URL" data-id="https://pyng.tech/docs/reportlab/lib/styles.m.html" target="_blank"><code>getSampleStyleSheet() </code></a>function. This function gives us access to default styles, such as <code>Title</code>, <code>Heading1</code>, <code>Heading2</code>, etc.  Additional styles can be found <a rel="noreferrer noopener" href="https://pyng.tech/docs/reportlab/lib/styles.m.html" data-type="URL" data-id="https://pyng.tech/docs/reportlab/lib/styles.m.html" target="_blank"><code>here</code></a>.</p>



<p>The following line calls the <a rel="noreferrer noopener" href="https://docs.reportlab.com/" data-type="URL" data-id="https://docs.reportlab.com/" target="_blank"><code>SimpleDocTemplate()</code></a> function and passes it five (5) arguments: the filename of the PDF to generate and the page margins. The results save to <code>doc</code>.</p>



<p>Save this file.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Step 6: Create Page Header</h2>



<p class="has-global-color-8-background-color has-background">This code snippet creates a header for each page of the PDF.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def createPageHeader():
    elements.append(Spacer(1, 10))
    elements.append(Image('car_logo.png', 100, 25))
    elements.append(Paragraph("Inventory", styles['Title']))
    elements.append(Spacer(1, 8))</pre>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<p>This first line in the above code snippet declares the function <code>createPageHeader()</code>. The contents of this function will appear at the top of each page.</p>



<p>The following line adds spacing from the top of the page using the <code><a rel="noreferrer noopener" href="https://www.reportlab.com/docs/reportlab-userguide.pdf" data-type="URL" data-id="https://www.reportlab.com/docs/reportlab-userguide.pdf" target="_blank">Spacer()</a></code> function and passing it two (2) arguments: the width and height. The results are appended to <code>elements</code>, declared at the beginning of the code. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" />To achieve the offset, the <code>topMargin</code> argument could also be adjusted. However, we wanted to show another way to achieve the same result.</p>



<p>The next line calls the <a rel="noreferrer noopener" href="https://www.reportlab.com/docs/reportlab-userguide.pdf" data-type="URL" data-id="https://www.reportlab.com/docs/reportlab-userguide.pdf" target="_blank"><code>Image()</code></a> function and passes it three (3) arguments: the image, and the x and y positions, respectively.</p>



<p>The results are appended to <code>elements</code>, declared at the beginning of the code.  </p>



<p>Then, a heading of <code>Inventory </code>is called using the <a rel="noreferrer noopener" href="https://www.reportlab.com/docs/reportlab-userguide.pdf" data-type="URL" data-id="https://www.reportlab.com/docs/reportlab-userguide.pdf" target="_blank"><code>Paragraph()</code></a> function and passing it two (2) arguments: the text and the style for the text. The results are appended to <code>elements</code>, declared at the beginning of the code. </p>



<p>The last line appends another <code><a rel="noreferrer noopener" href="https://www.reportlab.com/docs/reportlab-userguide.pdf" data-type="URL" data-id="https://www.reportlab.com/docs/reportlab-userguide.pdf" target="_blank">Spacer()</a></code>.</p>



<p>Save this file.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Step 7: Paginate the Data</h2>



<p class="has-global-color-8-background-color has-background">This code snippet shows how the data for each page is paginated.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def paginateInventory(start, stop):
    tbl = Table(df_data[0:1] + pg_data[start:stop])  
    tbl.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, 0), '#F5F5F5'),
                              ('FONTSIZE', (0, 0), (-1, 0), 8),
                              ('GRID', (0, 0), (-1, -1), .5, '#a7a5a5')])) 
    elements.append(tbl)</pre>



<p>The line in the above code snippet declares the function <code>paginateInventory()</code> which accepts two (2) arguments: a <code>start</code> and <code>stop</code> position.</p>



<p>The following line creates the data for the page. The <a rel="noreferrer noopener" href="https://www.reportlab.com/docs/reportlab-userguide.pdf" data-type="URL" data-id="https://www.reportlab.com/docs/reportlab-userguide.pdf" target="_blank"><code>Table()</code></a> function is called and passed one (1) argument: the header row from <code>df_data</code> (<code>df_data[0:1]</code>), plus the data for the specified page (<code>pg_data[start:stop]</code>). These results save to <code>tbl</code>.</p>



<p>The next line sets out the format for the table on the page. This line does the following:</p>



<ul class="wp-block-list">
<li>Change the background color of the header row.</li>



<li>Changes the font size.</li>



<li>Sets up the grid lines between all the cols/rows,</li>
</ul>



<p>The <code>tbl </code>is then appended to <code>elements</code>, declared at the beginning of the code. </p>



<p>Save this file.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="The Ultimate Guide to Slicing in Python" width="937" height="527" src="https://www.youtube.com/embed/D2ZueuWXST8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Step 8: Build the PDF</h2>



<p class="has-global-color-8-background-color has-background">This code snippet creates a function to loop through the paginated data and builds a PDF.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def generatePDF():
    cur_pg = 0
    start_pos = 0
    stop_pos = recs_pg

    for cur_pg in range(tot_pgs):
        createPageHeader()
        paginateInventory(start_pos, stop_pos)
        elements.append(PageBreak())
        start_pos += recs_pg
        stop_pos += recs_pg
    doc.build(elements)</pre>



<p>The first line in the above code snippet declares the function  <code>generatePDF()</code>. </p>



<p>The following three (3) lines declare three (3) variables and their initial positions.</p>



<ul class="wp-block-list">
<li><code>cur_pg</code>, which keeps track of the page we are currently on.</li>



<li><code>start_pos</code>, which is where the data initially starts.</li>



<li><code>stop_pos</code>, which is where the data initially ends (<code>recs_pg</code>, or 39).</li>
</ul>



<p>The following section does all the work! It declares a <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank">for</a></code> loop, which loops through all pre-determined pages (<code>tot_pgs</code>, or 2 in this case). Then, the following creates a page by:</p>



<ul class="wp-block-list">
<li>Executing the <code>createPageHeader()</code> function.</li>



<li>Outputting the page data using <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="post" data-id="731" target="_blank" rel="noreferrer noopener">slicing</a> (<code>paginateInventory(start_pos, stop_pos)</code>).</li>



<li>Adds a Page Break (<code>PageBreak()</code>).</li>



<li>Re-calculate the <code>start_pos</code> and <code>stop_pos</code> variables.</li>
</ul>



<p>This loop continues until all pages have been generated,</p>



<p>The last line in this code snippet, builds the PDF.</p>



<p>Save this file.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Step 9: Generate a PDF</h2>



<p class="has-global-color-8-background-color has-background">This code snippet generates the PDF built earlier.</p>



<p>If you ran the above code, no PDF file would be generated. This is because the following code needs to be appended to the end of the <code>pdf.py</code> file.</p>



<p>The first line is mainly used to declare the top-level starting point of a program.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">if __name__ == '__main__':
    generatePDF()</pre>



<p>An alternative is to just call the function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">generatePDF()</pre>



<p>There are pros and cons to both options. However, the choice is up to you.</p>



<p>Save and run this file.</p>



<p>If successful, the <code>inventory.pdf</code> file will be saved to the current working directory. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2022/11/inv_pdf.png" alt="" class="wp-image-928970" width="638" height="319" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/inv_pdf.png 770w, https://blog.finxter.com/wp-content/uploads/2022/11/inv_pdf-300x150.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/inv_pdf-768x385.png 768w" sizes="auto, (max-width: 638px) 100vw, 638px" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">The Full Code</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from reportlab.platypus import *
from reportlab.lib.styles import *
from reportlab.lib import *
from reportlab.platypus import *
import pandas as pd
import math 

df_cars = pd.read_csv('cars.csv', sep=';').head(60)
df_data = [df_cars.columns[:,].values.astype(str).tolist()] + df_cars.values.tolist()
pg_data = df_data[1:]

elements = []
recs_pg = 39
tot_pgs = math.ceil(len(df_data) / recs_pg)

styles = getSampleStyleSheet()
doc = SimpleDocTemplate('inventory.pdf', rightMargin=0, leftMargin=0, topMargin=0, bottomMargin=0)

def createPageHeader():
    elements.append(Spacer(1, 10))
    elements.append(Image('car_logo.png', 100, 25))
    elements.append(Paragraph("Inventory", styles['Title']))
    elements.append(Spacer(1, 8))

def paginateInventory(start, stop):
    tbl = Table(df_data[0:1] + pg_data[start:stop])  
    tbl.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, 0), '#F5F5F5'),
                              ('FONTSIZE', (0, 0), (-1, 0), 8),
                              ('GRID', (0, 0), (-1, -1), .5, '#a7a5a5')])) 
    elements.append(tbl)

def generatePDF():
    cur_pg = 0
    start_pos = 0
    stop_pos = recs_pg

    for cur_pg in range(tot_pgs):
        createPageHeader()
        paginateInventory(start_pos, stop_pos)
        elements.append(PageBreak())
        start_pos += recs_pg
        stop_pos += recs_pg
    doc.build(elements)
generatePDF()</pre>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Summary</h2>



<p>This article has shown you a compact way to generate a customized PDF file.</p>



<p>Good Luck &amp; Happy Coding!</p>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<p></p>
<p>The post <a href="https://blog.finxter.com/generate-a-simple-pdf-using-python-reportlab-9-steps/">Generate a Simple PDF using Python ReportLab (9 Steps)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Import External Code in Python</title>
		<link>https://blog.finxter.com/how-to-import-external-code-in-python/</link>
		
		<dc:creator><![CDATA[Kat McKelvie]]></dc:creator>
		<pubDate>Sat, 26 Nov 2022 12:23:30 +0000</pubDate>
				<category><![CDATA[Dependency Management]]></category>
		<category><![CDATA[Input/Output]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=924065</guid>

					<description><![CDATA[<p>Problem Formulation and Solution Overview This article will show you how to import external Python code and use this code in another Python script. To make it more interesting, we have the following running scenario: 👩‍🏫 Fun Example: Pam, a High School Teacher, wants an easier way to calculate exam totals and produce student averages. ... <a title="How to Import External Code in Python" class="read-more" href="https://blog.finxter.com/how-to-import-external-code-in-python/" aria-label="Read more about How to Import External Code in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-import-external-code-in-python/">How to Import External Code in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-heading">Problem Formulation and Solution Overview</h2>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">This article will show you how to import external Python code and use this code in another Python script.</p>



<p>To make it more interesting, we have the following running scenario:</p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f469-200d-1f3eb.png" alt="👩‍🏫" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Fun Example</strong>: <em>Pam, a High School Teacher, wants an easier way to calculate exam totals and produce student averages. The functions to produce these results are located in an external Python file. She has asked for your help.</em></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>To follow along, create a file called <code>calcs.py</code>. Copy and paste the contents shown below into this file. Save and place this file into the current working directory.</p>



<p><strong>Contents of calcs.py</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def ClassAverage(lst):
    return sum(lst) / len(lst)

def IncreaseGrades(lst):
    return [x+2 for x in lst]

def DecreaseGrades(lst):
    return [x-3 for x in lst]

def DecreaseGrades(lst):
    return [x-3 for x in lst]

def FailStudent(sname, el):
    return (f'Sorry {sname[el]} you failed.')</pre>



<hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio"/>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><em><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4ac.png" alt="💬" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </em><strong>Question</strong>: How would we write code to import and call these functions from another file?</p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task by one of the following options:</p>



<ul class="wp-block-list" type="video">
<li><strong>Method 1</strong>: Use <code>from file import function</code></li>



<li><strong>Method 2</strong>: Use <code>from file import *</code></li>



<li><strong>Method 3</strong>: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/functions.html#exec" data-type="URL" data-id="https://docs.python.org/3/library/functions.html#exec" target="_blank"><code>exec()</code></a></li>



<li><strong>Method 4</strong>: Use <code>import file</code></li>



<li><strong>Method 5</strong>: Run from a subfolder</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 1: Use &#8220;from file import function&#8221;</h2>



<p class="has-global-color-8-background-color has-background">This example calls in one (1) specific function from the <code>calcs.py</code> file, <code>ClassAverage()</code>. This code does <strong>not </strong>have access to any other functions from this file.</p>



<p>This code calculates the average grade for the Class.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1,4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from calcs import ClassAverage

std_grades = [76, 53, 68, 49, 81]
class_avg = ClassAverage(std_grades)
print(f'The Average Grade for the Class is {class_avg}%.')</pre>



<p>The first line in the above code snippet imports the <code>ClassAverage()</code> function from the <code>calcs.py</code> file. </p>



<p>The following line declares a <code><a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">list</a></code> of student grades. The results save to <code>std_grades</code>.</p>



<p>The next line calls in the <code>ClassAverage()</code> function and passes it one (1) argument, <code>std_grades</code>. The results of this calculation save to <code>class_avg</code> and are output to the terminal.</p>



<pre class="wp-block-preformatted"><code>The Average Grade for the Class is 65.4%.</code></pre>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Note</strong>: To import additional functions, place a comma after the first function as follows: <code>from calcs import Class Average, IncreaseGrades</code>.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 2: Use &#8220;from file import *&#8221;</h2>



<p class="has-global-color-8-background-color has-background">This example uses <code>import *</code>. This lets Python know that <strong>all</strong> functions are available to use.</p>



<p>This code increases the students&#8217; grades by two (2) grade points.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1,4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from calcs import *

std_grades = [76, 53, 68, 49, 81]
new_grades = IncreaseGrades(std_grades)
print(new_grades)</pre>



<p>The first line in the above code snippet imports all functions from the <code>calcs.py</code> file. </p>



<p>The following line declares a <code><a href="https://blog.finxter.com/python-lists/">list</a></code> of student grades. The results save to <code>std_grades</code>.</p>



<p>The next line calls the <code>IncreaseGrades()</code> function and passes it one (1) argument, <code>std_grades</code>. The results of this calculation save to <code>new_grades</code> and are output to the terminal.</p>



<pre class="wp-block-preformatted"><code>[78, 55, 70, 51, 83]</code></pre>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="A Simple Introduction to List Comprehension in Python" width="937" height="527" src="https://www.youtube.com/embed/9qsq2Vf48W8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 3: Use exec() and file.read()</h2>



<p class="has-global-color-8-background-color has-background">This example uses <a rel="noreferrer noopener" href="https://docs.python.org/3/library/functions.html#exec" data-type="URL" data-id="https://docs.python.org/3/library/functions.html#exec" target="_blank"><code>exec()</code></a> and <code>with open</code> to read in the contents of the <code>calcs.py</code> file.</p>



<p>This code decreases the students&#8217; grades and re-calculates the average grade.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1,4-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">with open('calcs.py') as fp: exec(fp.read())

std_grades = [76, 53, 68, 49, 81]
new_grades = DecreaseGrades(std_grades)
class_avg = ClassAverage(new_grades)

print(new_grades)
print(class_avg)</pre>



<p>The first line in the above code snippet reads in the <code>calcs.py</code> file and saves this as a File Object, <code>fp</code>. If output to the terminal, a File Object similar to below would display.</p>



<pre class="wp-block-preformatted"><code>&lt;_io.TextIOWrapper name='calcs.py' mode='r' encoding='cp1252'></code></pre>



<p>Then <code><a href="https://blog.finxter.com/python-exec/" data-type="post" data-id="18860" target="_blank" rel="noreferrer noopener">exec()</a></code> is called and passed one (1) argument, <a href="https://python-reference.readthedocs.io/en/latest/docs/file/read.html" data-type="URL" data-id="https://python-reference.readthedocs.io/en/latest/docs/file/read.html" target="_blank" rel="noreferrer noopener"><code>fp.read()</code></a>, which reads the contents of the file.</p>



<p>The following line declares a <code><a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">list</a></code> of student grades. The results save to <code>std_grades</code>.</p>



<p>The next line calls the <code>DecreaseGrades()</code> function and passes it one (1) argument, <code>std_grades</code>. The results of this calculation save to <code>new_grades</code>. </p>



<p>Then, the <code>ClassAverage()</code> function is called and passed one (1) argument, <code>new_grades</code>. The results of this calculation save to <code>class_avg</code>.</p>



<p>The contents of the above variables are output to the terminal.</p>



<pre class="wp-block-preformatted"><code>[73, 50, 65, 46, 78]
62.4</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 4: Use &#8220;import file&#8221;</h2>



<p class="has-global-color-8-background-color has-background">This example uses <code>from import</code>. To access the functions from the <code>calcs.py</code> file, you need a direct reference, such as <code>calcs.function()</code>.</p>



<p>This code informs the specified student they have failed. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1,5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import calcs

std_names = ['Amy', 'Ben', 'Art', 'Joe', 'Zoe']
std_grades = [76, 53, 68, 49, 81]
std_failed = calcs.FailStudent(std_names, 3)
print(std_failed)</pre>



<p>The first line in the above code snippet imports all functions from the <code>calcs.py</code> file. </p>



<p>The following two (2) lines declare a list of students and a corresponding list of grades. These results save to <code>std_names</code> and <code>std_grades</code>, respectively.</p>



<p>The next line calls the file name imported earlier (<code>calc</code>) and appends the function <code>FailStudent()</code>. This function is passed two (2) arguments, <code>std_names</code> and the index number of the failing student. The results save to <code>std_failed</code> and are output to the terminal.</p>



<pre class="wp-block-preformatted"><code>Sorry Joe you failed.</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 5: Run from a sub-folder</h2>



<p class="has-global-color-8-background-color has-background">This example places the <code>calcs.py</code> file inside the <code>test</code> folder. This file is then referenced in the code.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
import sys

subfolder = "test/"
sys.path.append(os.path.abspath(subfolder))

import calcs

std_grades = [76, 53, 68, 49, 81]
new_grades = calcs.DecreaseGrades(std_grades)
class_avg = calcs.ClassAverage(new_grades)
print(class_avg)</pre>



<p>The first (2) lines in the above code snippet import the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/os.html" data-type="URL" data-id="https://docs.python.org/3/library/os.html" target="_blank"><code>os</code></a> and the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/sys.html" data-type="URL" data-id="https://docs.python.org/3/library/sys.html" target="_blank"><code>sys</code></a> libraries used to locate the sub-folder.</p>



<p>The following two (2) lines let the code know to set the location to the <code>subfolder</code> (<code>test</code>). For this example, the <code>calcs.py</code> file resides in this folder.</p>



<p>The following line imports <code>calcs</code>.</p>



<p>To confirm this works, the final four (4) lines declare a list of students&#8217; grades and calculates the Class Average. The results are output to the terminal.</p>



<pre class="wp-block-preformatted"><code>62.4</code></pre>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Note</strong>: The above code is the same code used in <strong>Method 3 </strong>above.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Summary</h2>



<p>This article has provided five (5) ways to import a Python file to select the best fit for your coding requirements.</p>



<p>Good Luck &amp; Happy Coding!</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p></p>
<p>The post <a href="https://blog.finxter.com/how-to-import-external-code-in-python/">How to Import External Code in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Create, Update, and Query an SQLite Database in Python?</title>
		<link>https://blog.finxter.com/how-to-create-update-and-query-an-sqlite-database-in-python/</link>
		
		<dc:creator><![CDATA[Kat McKelvie]]></dc:creator>
		<pubDate>Thu, 24 Nov 2022 10:27:31 +0000</pubDate>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=917299</guid>

					<description><![CDATA[<p>Problem Formulation and Solution Overview This article will show you how to create, update and query a SQLite database using Python. ℹ️The SQLite database is a great choice! It is self-contained, easy to use, easy to learn, and works on other devices, such as game consoles, mobile phones, and so on! To make it more ... <a title="How to Create, Update, and Query an SQLite Database in Python?" class="read-more" href="https://blog.finxter.com/how-to-create-update-and-query-an-sqlite-database-in-python/" aria-label="Read more about How to Create, Update, and Query an SQLite Database in Python?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-create-update-and-query-an-sqlite-database-in-python/">How to Create, Update, and Query an SQLite Database in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-heading">Problem Formulation and Solution Overview</h2>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">This article will show you how to create, update and query a SQLite database using Python.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" />The SQLite database is a great choice! It is self-contained, easy to use, easy to learn, and works on other devices, such as game consoles, mobile phones, and so on! </p>



<p>To make it more interesting, we have the following running scenario:</p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio"><em>KarTech, a used car dealership in Toronto, currently has its inventory of cars saved as a CSV file format. However, they would like this imported into a database. For simplicity, they selected SQLite.</em></p>



<p>To follow along with this article, <a rel="noreferrer noopener" href="https://blog.finxter.com/wp-content/uploads/2022/11/cars.csv" data-type="URL" data-id="https://blog.finxter.com/wp-content/uploads/2022/11/cars.csv" target="_blank">download</a> and place the <code>cars.csv</code> file into the current working directory:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://blog.finxter.com/wp-content/uploads/2022/11/cars.csv" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="933" height="832" src="https://blog.finxter.com/wp-content/uploads/2022/11/image-267.png" alt="" class="wp-image-921281" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/image-267.png 933w, https://blog.finxter.com/wp-content/uploads/2022/11/image-267-300x268.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/image-267-768x685.png 768w" sizes="auto, (max-width: 933px) 100vw, 933px" /></a></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio" />



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4ac.png" alt="💬" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write code to create and work with a SQLite Database<em>?</em></p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task by performing the following these steps:</p>



<ul class="wp-block-list" type="video">
<li><strong>Preparation</strong></li>



<li><strong>Declare Variables</strong></li>



<li><strong>Create SQLite Database and Table</strong></li>



<li><strong>Retrieve Table Column Names</strong></li>



<li><strong>Execute Select Query</strong></li>



<li><strong>Execute Insert <strong>Query</strong></strong></li>



<li><strong>Execute Delete <strong>Query</strong></strong></li>



<li><strong>Close Connections</strong></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Preparation</h2>



<p class="has-global-color-8-background-color has-background">The first step is to import and install the required library to ensure the code in this article will run error-free.</p>



<p>If the <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="URL" data-id="https://blog.finxter.com/pandas-quickstart/" target="_blank"><code>pandas</code></a> library is not installed. Click <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-pandas-in-python/" target="_blank">here</a> for instructions. </p>



<p>Next, create a Python file in the current working directory called <code>cars-sql.py</code> and paste the following code to the top of this file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
import sqlite3
from os.path import exists as file_exists</pre>



<p>The first line in the above code snippet calls in the <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="URL" data-id="https://blog.finxter.com/pandas-quickstart/" target="_blank"><code>pandas</code></a> library, which is required to access and manipulate the <code>cars.csv</code> file downloaded earlier.</p>



<p>The following line imports Python&#8217;s built-in <code><a href="https://docs.python.org/3/library/sqlite3.html" data-type="URL" data-id="https://docs.python.org/3/library/sqlite3.html" target="_blank" rel="noreferrer noopener">sqlite3</a></code> library required to access and manipulate the SQLite database.</p>



<p>The last line also imports Python&#8217;s built-in <code><a href="https://blog.finxter.com/exploring-pythons-os-module/" data-type="post" data-id="19050" target="_blank" rel="noreferrer noopener">os</a></code> library that checks for the existence of the Database file.</p>



<p>Save this file.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="10 Minutes to Pandas in 5 Minutes (Okay 8)" width="937" height="527" src="https://www.youtube.com/embed/-JKVy_HliQE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Declare Variables</h2>



<p class="has-global-color-8-background-color has-background">This section creates and assigns variables for the Database, its associated Table, and the <code>cars.csv</code> file downloaded earlier.</p>



<p>Paste the following lines to the bottom of the <code>cars-sql.py</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dbase_name = 'cars.db'
table_name = 'inventory'
csv_file = 'cars.csv'</pre>



<p>Save this file.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Create Database and Table</h2>



<p class="has-global-color-8-background-color has-background">This section does all the heavy lifting! It creates a Database if it does not already exist and attempts to connect to the same!</p>



<p>Paste the following lines to the bottom of the <code>cars-sql.py</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">if file_exists(dbase_name):
    conn = sqlite3.connect(dbase_name)
else:
    conn = sqlite3.connect(dbase_name)
    df = pd.read_csv('cars.csv', sep=';')
    df.to_sql(f'{table_name}', conn)
cur = conn.cursor()</pre>



<p>The first line in the above code snippet checks to see if the Database exists in the current working directory (<code>cars.db</code>).  If this file exists, a Connection Object is created (<code>conn</code>), allowing access to the Database (shown below).</p>



<pre class="wp-block-preformatted"><code>Connection Object: &lt;sqlite3.Connection object at 0x000001E8653DAB40&gt;</code></pre>



<p>If the Database does <strong>not</strong> exist, code execution falls inside the <code>else</code> statement where the following occurs:</p>



<ul class="wp-block-list">
<li>A Database is created, and a <code>Connection</code> object to the same saves to <code>conn</code>.</li>



<li>The <code>cars.csv</code> file is read in (notice the separator character). The results save to the DataFrame, <code>df</code>.</li>



<li>Then the contents of <code>df</code> are imported into the table specified earlier (<code>inventory</code>).</li>
</ul>



<p>The last line creates a Cursor Object (<code>cur</code>) from the Connection Object (<code>conn</code>). The Cursor Object allows access to commands, such as SQL, which can be applied against the Database and/or Table.</p>



<pre class="wp-block-preformatted"><code>Cursor Object: &lt;sqlite3.Cursor object at 0x0000024D38B562C0&gt;</code></pre>



<p>Save this file.</p>



<p>If successful, the <code>cars.db</code> SQLite database should now reside in the current working directory.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Retrieve Table Column Names</h2>



<p class="has-global-color-8-background-color has-background">This section shows how to retrieve a list of the Column Names in the Table.</p>



<p>Paste the following lines to the bottom of the <code>cars-sql.py</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cols = conn.execute('SELECT * FROM inventory')
conn.commit()

col_names = list(map(lambda x: x[0], cols.description))</pre>



<p>The first two (2) lines in the above code snippet execute and commit a SQL command that receives all rows from the <code>inventory</code> Table. A Cursor Object is created from these results and saved to <code><code><code>cols</code></code></code>. If output to the terminal, the following would display.</p>



<pre class="wp-block-preformatted"><code>Cols Object: &lt;sqlite3.Cursor object at 0x0000022582C9CBC0&gt;</code></pre>



<p>The following lines access and retrieve the <code>cols.description</code> field using a <a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank"><code>lambda</code></a>, a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-map/" target="_blank"><code>map()</code></a>, and a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a>. This action retrieves the Field Names from the Table and saves the results to <code>tbl_fields</code>. If output to the terminal, the following would display.</p>



<pre class="wp-block-preformatted"><code>['index', 'Car', 'MPG', 'Cylinders', 'Displacement', 'Horsepower', 'Weight', 'Acceleration', 'Model', 'Origin']</code></pre>



<p>Save this file.</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Note</strong>: The<code> <a rel="noreferrer noopener" href="https://www.sqlite.org/lang_transaction.html" data-type="URL" data-id="https://www.sqlite.org/lang_transaction.html" target="_blank">commit()</a></code> command saves changes invoked by a SQL query to the database. Click <a href="https://www.sqlite.org/index.html" data-type="URL" data-id="https://www.sqlite.org/index.html" target="_blank" rel="noreferrer noopener">here</a> to learn more.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Let&#039;s Play Finxter - The Lambda Function in Python" width="937" height="527" src="https://www.youtube.com/embed/kBg4n52XoUQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Execute Select Query</h2>



<p class="has-global-color-8-background-color has-background">This section shows how to create and execute a SELECT query. </p>



<p>Paste the following lines to the bottom of the <code>cars-sql.py</code> file.</p>



<p>When executing a SELECT query, this task can be performed using the <a rel="noreferrer noopener" href="https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.read_sql.html" data-type="URL" data-id="https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.read_sql.html" target="_blank"><code>read_sql()</code></a> function and passing it two (2) arguments, a SQL statement and a Connection Object (<code>conn</code>). </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">query = pd.read_sql(f'SELECT Car, MPG, Cylinders FROM {table_name} LIMIT 5', conn)</pre>



<p>This SQL query selects and retrieves three (3) columns and five (5) rows from the <code>inventory</code> table. The results save to <code>query</code>. If output to the terminal, the following would display.</p>



<pre class="wp-block-preformatted"><code>   Car</code>                                                    <code>MPG      Cylinders
0  Chevrolet Chevelle Malibu                18.0             8
1  Buick Skylark 320                             15.0             8
2  Plymouth Satellite                             18.0             8
3  AMC Rebel SST                                16.0             8
4  Ford Torino                                        17.0             8</code></pre>



<p>Save this file.</p>



<p class="has-global-color-8-background-color has-background"><strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Note</strong>: The above method is commonly used for SELECT queries as we are not altering the Database or the Table, such as performing an update, insert, delete, drop, or alter command. Click <a rel="noreferrer noopener" href="https://www.w3schools.com/sql/" data-type="URL" data-id="https://www.w3schools.com/sql/" target="_blank">here</a> to learn more about SQL.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Execute Insert Query</h2>



<p class="has-global-color-8-background-color has-background">This section outlines how to create and execute an INSERT query</p>



<p>Paste the following lines to the bottom of the <code>cars-sql.py</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cur.execute('''INSERT INTO inventory
             VALUES('Citroen', '28.0', '8', '', '', '', '', '', '', '')''')

print(cur.lastrowid)
conn.commit()</pre>



<p>The first line in the above code snippet creates and executes a SQL statement that INSERTS one (1) record into the <code>inventory</code> Table.</p>



<p>The following line retrieves the Row ID and is output to the terminal. If this returns an integer value, then the INSERT was successful. </p>



<pre class="wp-block-preformatted"><code>408</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Execute Delete Query</h2>



<p class="has-global-color-8-background-color has-background">This section outlines how to create and execute a DELETE query</p>



<p>Paste the following lines to the bottom of the <code>cars-sql.py</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cur.execute('''DELETE FROM inventory WHERE MPG = 28.0''')
conn.commit()</pre>



<p>The first line in the above code snippet creates and executes a SQL statement that DELETES all records matching the criteria from the <code>inventory</code> Table.</p>



<p>The following line commits the changes to the Database.</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Note</strong>: Run a SELECT query to see if the record(s) were successfully deleted.</p>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Close the Connections</h2>



<p class="has-global-color-8-background-color has-background">The final step is to close any open connections.</p>



<p>Paste the following lines to the bottom of the <code>cars-sql.py</code> file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cur.close()
conn.close()</pre>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">The Entire Script</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
import sqlite3
from os.path import exists as file_exists

dbase_name = 'cars.db'
table_name = 'inventory'
csv_file = 'cars.csv'

if file_exists(dbase_name):
    conn = sqlite3.connect(dbase_name)
else:
    conn = sqlite3.connect(dbase_name)
    df = pd.read_csv('cars.csv', sep=';')
    df.to_sql(f'{table_name}', conn)
cur = conn.cursor()


# Get Column Names
cols = conn.execute('SELECT * FROM inventory')
conn.commit()
col_names = list(map(lambda x: x[0], cols.description))

# SELECT
query = pd.read_sql(f'SELECT Car, MPG, Cylinders FROM {table_name} LIMIT 5', conn)
print(query)

# INSERT
cur.execute('''INSERT INTO inventory
             VALUES('Citroen', '28.0', '8', '', '', '', '', '', '', '')''')

print(cur.lastrowid)
conn.commit()

# DELETE
cur.execute('''DELETE FROM inventory WHERE MPG = 28.0''')
conn.commit()

cur.close()
conn.close()</pre>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<h2 class="wp-block-heading">Summary</h2>



<p>This article has shown you how to work with a SQLite Database.</p>



<p>Good Luck &amp; Happy Coding!</p>



<hr class="wp-block-separator has-alpha-channel-opacity" />



<p></p>
<p>The post <a href="https://blog.finxter.com/how-to-create-update-and-query-an-sqlite-database-in-python/">How to Create, Update, and Query an SQLite Database in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Interpolate Strings</title>
		<link>https://blog.finxter.com/how-to-interpolate-strings/</link>
		
		<dc:creator><![CDATA[Kat McKelvie]]></dc:creator>
		<pubDate>Tue, 22 Nov 2022 14:21:53 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Python String]]></category>
		<category><![CDATA[Text Processing]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=906848</guid>

					<description><![CDATA[<p>Problem Formulation and Solution Overview This article will show you how to interpolate strings in Python. ℹ️ Interpolation is used when a string contains a placeholder for a variable or a calculation. The string is evaluated, and the placeholder is replaced by the passed data. To make it more interesting, we have the following running ... <a title="How to Interpolate Strings" class="read-more" href="https://blog.finxter.com/how-to-interpolate-strings/" aria-label="Read more about How to Interpolate Strings">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-interpolate-strings/">How to Interpolate Strings</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-heading">Problem Formulation and Solution Overview</h2>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">This article will show you how to interpolate strings in Python.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Interpolation</strong> is used when a string contains a placeholder for a variable or a calculation. The string is evaluated, and the placeholder is replaced by the passed data.</p>



<p>To make it more interesting, we have the following running scenario:</p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio"><em>Derek, a mortgage broker, wants to write a form email to his clients about the latest hike in mortgage rates. Your job is to create the body of the form email, and Derek will take care of the rest.</em></p>



<hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio"/>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4ac.png" alt="💬" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write code to interpolate strings in Python<em>?</em></p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task by one of the following options:</p>



<ul class="wp-block-list" type="video">
<li><strong>Method </strong>1: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/string.html" data-type="URL" data-id="https://docs.python.org/3/library/string.html" target="_blank"><code>template()</code></a> and <a href="https://docs.python.org/3/library/string.html" data-type="URL" data-id="https://docs.python.org/3/library/string.html" target="_blank" rel="noreferrer noopener"><code>substitute()</code></a></li>



<li><strong>Method </strong>2: Use <a href="https://docs.python.org/3/tutorial/inputoutput.html" data-type="URL" data-id="https://docs.python.org/3/tutorial/inputoutput.html" target="_blank" rel="noreferrer noopener"><code>f-string</code></a></li>



<li><strong>Method </strong>3: Use the % operator</li>



<li><strong>Method 4</strong>: Use <a href="https://blog.finxter.com/python-format-function/" data-type="post" data-id="22855" target="_blank" rel="noreferrer noopener"><code>format()</code></a></li>



<li><strong>Bonus</strong>: Putting it Together</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 1: Use template() and substitute()</h2>



<p class="has-global-color-8-background-color has-background">This method calls <code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/string.html" data-type="URL" data-id="https://docs.python.org/3/library/string.html" target="_blank">string.Template()</a></code> and uses a dollar sign (<code>$</code>) and a variable name to define a placeholder (<code>$first_name</code>). Whereas <a rel="noreferrer noopener" href="https://docs.python.org/3/library/string.html" data-type="URL" data-id="https://docs.python.org/3/library/string.html" target="_blank"><code>substitute()</code></a> replaces that placeholder with the specified data.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4,7" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import string

clients = ['Bill', 'Micah', 'Philip', 'Josiah']
salutation = string.Template('Dear $first_name,\n')

for fname in clients:
    print(salutation.substitute(first_name=fname))</pre>



<p>The first line in the above code snippet imports the <a href="https://docs.python.org/3/library/string.html" data-type="URL" data-id="https://docs.python.org/3/library/string.html" target="_blank" rel="noreferrer noopener"><code>string</code></a> library. This is required because <code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/string.html" data-type="URL" data-id="https://docs.python.org/3/library/string.html" target="_blank">string.Template()</a></code> and <a rel="noreferrer noopener" href="https://docs.python.org/3/library/string.html" data-type="URL" data-id="https://docs.python.org/3/library/string.html" target="_blank"><code>substitute()</code></a> are being called.</p>



<p>The following line declares a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a> of client names. The results save to <code>clients</code>.</p>



<p>The highlighted line declares <code>string.Template()</code> and passes this one (1) argument: the formatted <code>salutation</code>. This string consists of the word <code>Dear</code> and a placeholder, <code>$first_name</code>, followed by a comma and a newline character (<code>,</code>\n).</p>



<p>In the following two (2) lines, a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> loop iterates through this <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a>, substituting the <code>salutation</code> placeholder with the client&#8217;s first name. The results are then output to the terminal.</p>



<pre class="wp-block-preformatted"><code>Dear Bill,

Dear Micah,

Dear Philip,

Dear Josiah,</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 2: Use f-string</h2>



<p class="has-global-color-8-background-color has-background">This method uses an <code><a href="https://blog.finxter.com/string-formatting-vs-format-vs-formatted-string-literal/" data-type="post" data-id="13190" target="_blank" rel="noreferrer noopener">f-string</a></code> with the curly braces (<code>{}</code>) as a placeholder. This placeholder is replaced with the specified data.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">clients = ['Bill', 'Micah', 'Philip', 'Josiah']

for fname in clients:
    print(f'{fname}, I just wanted to touch base with you.\n')</pre>



<p>The first line in the above code snippet declares a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a> of client names. The results save to <code>clients</code>.</p>



<p>In the following two (2) lines, a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> loop iterates through this <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a>, substituting the <code>{fname}</code> placeholder with the client&#8217;s name followed by a period and a newline character (<code>.\n</code>). The results are then output to the terminal.</p>



<pre class="wp-block-preformatted"><code>Bill, I just wanted to touch base with you.

Micah, I just wanted to touch base with you.

Philip, I just wanted to touch base with you.

Josiah, I just wanted to touch base with you.</code></pre>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Note</strong>:  In this example, the f-string is called inside the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="URL" data-id="https://blog.finxter.com/python-print/" target="_blank"><code>print()</code></a> statement to indicate to Python to expect a placeholder substitution and output the results to the terminal.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Print Function [And Its SECRET Separator &amp; End Arguments]" width="937" height="527" src="https://www.youtube.com/embed/yXhEvg8Domk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 3: Use the Percentage Operator %</h2>



<p class="has-global-color-8-background-color has-background">The <code>%</code> operator, although an older method, still works and can be used as a placeholder.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">m_rates = [3.725, 4.122, 5.398, 2.409]

for r in m_rates:
    print('Your current mortgage rate is %.3f.\n' % (r))</pre>



<p>The first line in the above code snippet declares a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a> of mortgage rates associated to the <code>clients</code> <code>list</code> created earlier. The results save to <code>m_rates</code>.</p>



<p>In the following two (2) lines, a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> loop iterates through this <code>list</code>, substituting the <code>%</code> placeholder with the client&#8217;s mortgage rate (with 3 <a href="https://blog.finxter.com/how-to-specify-the-number-of-decimal-places-in-python/" data-type="post" data-id="125693" target="_blank" rel="noreferrer noopener">decimal places</a>) followed by a period and a newline character (<code>,</code>\n). The results are then output to the terminal.</p>



<pre class="wp-block-preformatted"><code>Your current mortgage rate is 3.73.

Your current mortgage rate is 4.12.

Your current mortgage rate is 5.40.

Your current mortgage rate is 2.41.</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 4: Use format()</h2>



<p class="has-global-color-8-background-color has-background">This method uses empty curly braces(<code>{}</code>) as a placeholder and calls <a href="https://blog.finxter.com/python-string-format/" data-type="post" data-id="26013" target="_blank" rel="noreferrer noopener"><code>format()</code></a> to identify the field(s) to replace with the specified data.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">clients = ['Bill', 'Micah', 'Philip', 'Josiah']
new_rate = 7.876

for fname in clients:
    print('Your mortgage is renewing soon, and the new rate is {}%.\n'.format(new_rate))</pre>



<p>The first two lines in the above code snippet declare a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a> of client names and the new mortgage. These save to <code>clients</code> and <code>new_rate</code>, respectively.</p>



<p>In the following two (2) lines, a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> loop iterates through the <code>client</code> <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a>, substituting the <code>()</code> placeholder with the client&#8217;s new rate followed by a percent sign, a period, and a newline character (<code>,\n</code>). The results are then output to the terminal.</p>



<pre class="wp-block-preformatted"><code>Your mortgage is renewing soon, and the new rate is 7.876%.

Your mortgage is renewing soon, and the new rate is 7.876%.

Your mortgage is renewing soon, and the new rate is 7.876%.

Your mortgage is renewing soon, and the new rate is 7.876%.</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Bonus: Putting it Together</h2>



<p class="has-global-color-8-background-color has-background">This code loops through the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a> of clients to create a customized body for each email. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">clients = ['Bill', 'Micah', 'Philip', 'Josiah']
m_rates = [3.725, 4.122, 5.398, 2.409]
new_rate = 7.876
i = 0

for c in clients:
    body_text = ''
    str1 = f'Dear {c},\n\n'
    str2 = f'{c}, I just wanted to touch base with you.\n'
    str3 = f'Your current mortgage rate is {m_rates[i]}%.\n'
    str4 = f'Your mortgage is up for renewal and new rate is {new_rate}%.\n'
    str5 = 'Contact me for alternate rates.\n\n'
    body_text += str1 + str2 + str3 + str4 + str5
    print(body_text)
    i += 1</pre>



<p>The result is output to the terminal.</p>



<pre class="wp-block-preformatted"><code>Dear Bill,

Bill, I just wanted to touch base with you.
Your current mortgage rate is 3.725%.
Your mortgage is up for renewal and new rate is 7.876%.
Contact me for alternate rates.


Dear Micah,

Micah, I just wanted to touch base with you.
Your current mortgage rate is 4.122%.
Your mortgage is up for renewal and new rate is 7.876%.
Contact me for alternate rates.


Dear Philip,

Philip, I just wanted to touch base with you.
Your current mortgage rate is 5.398%.
Your mortgage is up for renewal and new rate is 7.876%.
Contact me for alternate rates.


Dear Josiah,

Josiah, I just wanted to touch base with you.
Your current mortgage rate is 2.409%.
Your mortgage is up for renewal and new rate is 7.876%.
Contact me for alternate rates.</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Summary</h2>



<p>This article has provided four (4) ways to interpolate strings to select the best fit for your coding requirements.</p>



<p>Good Luck &amp; Happy Coding!</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Programming Humor &#8211; Python</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="518" height="588" src="https://blog.finxter.com/wp-content/uploads/2022/07/image-65.png" alt="" class="wp-image-471102" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/image-65.png 518w, https://blog.finxter.com/wp-content/uploads/2022/07/image-65-264x300.png 264w" sizes="auto, (max-width: 518px) 100vw, 518px" /><figcaption><em>&#8220;I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I&#8217;m leaving you.&#8221;</em> &#8212; <a rel="noreferrer noopener" href="https://imgs.xkcd.com/comics/python.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/python.png" target="_blank">xkcd</a></figcaption></figure>
</div><p>The post <a href="https://blog.finxter.com/how-to-interpolate-strings/">How to Interpolate Strings</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>7 Pythonic Ways to Copy a Dictionary</title>
		<link>https://blog.finxter.com/7-ways-to-copy-a-dictionary-in-python/</link>
		
		<dc:creator><![CDATA[Kat McKelvie]]></dc:creator>
		<pubDate>Thu, 17 Nov 2022 00:34:30 +0000</pubDate>
				<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Dictionary]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=897202</guid>

					<description><![CDATA[<p>Problem Formulation and Solution Overview This article will show you how to copy a Dictionary in Python 7 different ways. To make it more interesting, we have the following running scenario: Mr. Smith, a High School Math Teacher, has developed an exciting way to grade multiple-choice exams. He has designed a Dictionary with the exam ... <a title="7 Pythonic Ways to Copy a Dictionary" class="read-more" href="https://blog.finxter.com/7-ways-to-copy-a-dictionary-in-python/" aria-label="Read more about 7 Pythonic Ways to Copy a Dictionary">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/7-ways-to-copy-a-dictionary-in-python/">7 Pythonic Ways to Copy a Dictionary</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-heading">Problem Formulation and Solution Overview</h2>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">This article will show you how to copy a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> in Python 7 different ways.</p>



<p>To make it more interesting, we have the following running scenario:</p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio"><em>Mr. Smith, a High School Math Teacher, has developed an exciting way to grade multiple-choice exams. He has designed a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" target="_blank"><code>Dictionary</code></a> with the exam question number and answer as key:value pairs. How can Mr. Smith make a copy of this structure to modify for future exams?</em></p>



<pre class="wp-block-preformatted"><code>exam_format = {1: 'B', 2: 'E', 3: 'C', 4: 'D', 5: 'D'}</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio"/>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4ac.png" alt="💬" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write code to create a copy of a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> in Python<em>?</em></p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task using one of the following options:</p>



<ul class="wp-block-list" type="video">
<li><strong>Method </strong>1: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dict/" data-type="URL" data-id="https://blog.finxter.com/python-dict/" target="_blank"><code>dict()</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary-comprehension/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank">Dictionary Comprehension</a></li>



<li><strong>Method </strong>2: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary-comprehension/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank">Dictionary Comprehension</a></li>



<li><strong>Method </strong>3: Use <a href="https://blog.finxter.com/python-dictionary-update-method/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-update-method/" target="_blank" rel="noreferrer noopener"><code>update()</code></a></li>



<li><strong>Method 4</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/what-is-asterisk-in-python/" data-type="URL" data-id="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank">Unpacking</a></li>



<li><strong>Method 5</strong>: Use <a href="https://docs.python.org/3/library/copy.html" data-type="URL" data-id="https://docs.python.org/3/library/copy.html" target="_blank" rel="noreferrer noopener"><code>copy()</code></a></li>



<li><strong>Method 6</strong>: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/copy.html" data-type="URL" data-id="https://docs.python.org/3/library/copy.html" target="_blank"><code>deepcopy()</code></a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 1: Use dict() and Dictionary Comprehension</h2>



<p class="has-global-color-8-background-color has-background">This method uses the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dict/" data-type="URL" data-id="https://blog.finxter.com/python-dict/" target="_blank"><code>dict()</code></a> function to create and return a new <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> object</p>



<p><strong>Example 1: </strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1,3-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">q1_exam = dict(exam_format)

q1_exam[1] = 'C'
q1_exam[2] = 'D'
q1_exam[5] = 'A'
print(q1_exam)</pre>



<p>The first line in the above code snippet uses the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dict/" data-type="URL" data-id="https://blog.finxter.com/python-dict/" target="_blank"><code>dict()</code></a> function and passes it one (1) argument: <code>exam_format</code> (created earlier). These results save to <code>q1_exam</code>.</p>



<p>The following lines modify three (3) values for the <code>q1_exam</code>. The results are output to the terminal.</p>



<pre class="wp-block-preformatted"><code>q1_exam:        {1: 'B', 2: 'E', 3: 'C', 4: 'D', 5: 'D'}</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p><strong>Example 2:</strong></p>



<p>Alternatively, we could call the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dict/" data-type="URL" data-id="https://blog.finxter.com/python-dict/" target="_blank"><code>dict()</code></a> function and pass it <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary-comprehension/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank">Dictionary Comprehension</a> as an argument to the same.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">q1_exam = dict((k,v) for k, v in exam_format.items())

q1_exam[1] = 'C'
q1_exam[2] = 'D'
q1_exam[5] = 'A'
print(q1_exam)  </pre>



<p>The output is identical to that shown above.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python dict() — A Simple Guide" width="937" height="527" src="https://www.youtube.com/embed/Y3oVGAOdr8M?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 2: Use Dictionary Comprehension</h2>



<p class="has-global-color-8-background-color has-background">This method uses <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary-comprehension/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank">Dictionary Comprehension</a> to create and return a new <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> object.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">q2_exam = {k:v for k,v in exam_format.items()}

q2_exam[2] = 'B'
q2_exam[3] = 'E'
q2_exam[5] = 'A'

print(q2_exam) </pre>



<p>The first line in the above code snippet uses <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank">Dictionary Comprehension</a> to create a copy of the <code>exam_format</code> (created earlier). These results save to <code>q2_exam</code>.</p>



<p>The following lines modify three (3) values for the <code>q2_exam</code>. These results are then output to the terminal.</p>



<pre class="wp-block-preformatted"><code>q2_exam:        {1: 'B', 2: 'B', 3: 'E', 4: 'D', 5: 'A'}</code></pre>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Dictionary Comprehension - A Powerful One-Liner Tutorial" width="937" height="527" src="https://www.youtube.com/embed/TlEC5Jx72Uc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 3: Use update()</h2>



<p class="has-global-color-8-background-color has-background">This method uses the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary-update-method/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-update-method/" target="_blank"><code>update()</code></a> function to create and return a new <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> object.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1-2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">q3_exam = {}
q3_exam.update(exam_format)
print(q3_exam)  </pre>



<p>The first line in the above code snippet declares an empty <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a>. These results save to <code>q3_exam</code>.</p>



<p>The following line calls <code>q3_exam</code> and appends the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary-update-method/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-update-method/" target="_blank"><code>update()</code></a> function to it. This function is passed one (1) argument: <code>exam_format</code> (created earlier).  These results are then output to the terminal.</p>



<pre class="wp-block-preformatted"><code>q3_exam:        {1: 'B', 2: 'E', 3: 'C', 4: 'D', 5: 'D'}</code></pre>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Dictionary update() Method" width="937" height="703" src="https://www.youtube.com/embed/y7A8uLfGEfo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 4: Use unpacking()</h2>



<p class="has-global-color-8-background-color has-background">This method uses the <a rel="noreferrer noopener" href="https://blog.finxter.com/what-is-asterisk-in-python/" data-type="URL" data-id="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank"><code>unpacking</code></a> function to create and return a new <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> object.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">q4_exam = {**exam_format}
print(q4_exam)  </pre>



<p>The first line in the above code snippet creates a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> and, using <a rel="noreferrer noopener" href="https://blog.finxter.com/what-is-asterisk-in-python/" data-type="URL" data-id="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank"><code>unpacking</code></a>, passes all elements of <code>exam_format</code>. These results save to <code>q4_exam</code>. How Pythonic!</p>



<p>The results are output to the terminal.</p>



<pre class="wp-block-preformatted"><code>q4_exam:        {1: 'B', 2: 'E', 3: 'C', 4: 'D', 5: 'D'}</code></pre>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Asterisk operator" width="937" height="527" src="https://www.youtube.com/embed/-nLkYmIevwY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="has-text-align-center has-base-3-color has-global-color-9-background-color has-text-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2728.png" alt="✨" class="wp-smiley" style="height: 1em; max-height: 1em;" />A Finxter Favourite!</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 5: Use copy()</h2>



<p class="has-global-color-8-background-color has-background">This method uses the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/copy.html" data-type="URL" data-id="https://docs.python.org/3/library/copy.html" target="_blank"><code>copy()</code></a> function to create and return a new <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> object. This function is referred to as a <em>shallow</em> copy as it creates references to the original Dictionary. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-5, 7-9" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import copy

exam_format2 = {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}
mid_term = exam_format2.copy()
print(mid_term)

mid_term[1].append(4)
print(exam_format2)
print(mid_term)</pre>



<p>The first line in the above code snippet imports the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/copy.html" data-type="URL" data-id="https://docs.python.org/3/library/copy.html" target="_blank"><code>copy</code></a> library. This allows access to the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/copy.html" data-type="URL" data-id="https://docs.python.org/3/library/copy.html" target="_blank"><code>copy()</code></a> function.</p>



<p>The following line declares a new exam format for <em>Mid Term</em> exams. The results save to <code>exam_format2</code>. Next, a shallow copy of this <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank"><code>Dictionary</code></a> is made by appending the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/copy.html" data-type="URL" data-id="https://docs.python.org/3/library/copy.html" target="_blank"><code>copy()</code></a> function to <code>exam_format2</code>. These results save to <code>mid_term</code> and are then output to the terminal.</p>



<pre class="wp-block-preformatted"><code>mid_term:        {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}</code></pre>



<p>The following highlighted section adds a new element to <code>mid_term</code> then, <code>exam_format2</code> and <code>mid_term</code> are then output to the terminal. </p>



<pre class="wp-block-preformatted"><code>exam_format2:     {1: [1, 2, 3, <strong>4</strong>], 2: [1, 2, 3], 3: [1, 2, 3]}
mid_term:         {1: [1, 2, 3, <strong>4</strong>], 2: [1, 2, 3], 3: [1, 2, 3]}</code></pre>



<p>Notice how both are updated. When coding, be careful with this option, as it may cause issues.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 6: deepcopy()</h2>



<p class="has-global-color-8-background-color has-background">This method uses the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/copy.html" data-type="URL" data-id="https://docs.python.org/3/library/copy.html" target="_blank"><code>deepcopy()</code></a> function to create and return a new <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> object. This function is called a deep copy as it creates a <em>new </em><a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> object. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-5, 7-9" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import copy

exam_format2 = {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}
mid_term = copy.deepcopy(exam_format2)
print(mid_term)

mid_term[1].append(4)
print(exam_format2)
print(mid_term)</pre>



<p>The above code snippet is almost the same as in <strong>Method 5</strong> (<code>copy()</code>). However, this code calls the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/copy.html" data-type="URL" data-id="https://docs.python.org/3/library/copy.html" target="_blank"><code>deepcopy()</code></a> function and passes it one (1) argument: <code>exam_format2</code>. The results save to <code>mid_term </code>and are then output to the terminal.</p>



<pre class="wp-block-preformatted"><code>mid_term:        {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}</code></pre>



<p>The following highlighted section adds a new element to <code>mid_term</code> then, <code>exam_format2</code> and <code>mid_term</code> are then output to the terminal. </p>



<pre class="wp-block-preformatted"><code>exam_format2:     {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}
mid_term:         {1: [1, 2, 3, <strong>4</strong>], 2: [1, 2, 3], 3: [1, 2, 3]}</code></pre>



<p>Using <a rel="noreferrer noopener" href="https://docs.python.org/3/library/copy.html" data-type="URL" data-id="https://docs.python.org/3/library/copy.html" target="_blank"><code>deepcopy()</code></a>, only <code>mid_term </code>was updated.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Bonus: Putting it Together</h2>



<p>We decided that <strong>Method 4</strong> was the best way to go, and we wrote the code below using this option.</p>



<p>The grade is automatically calculated when Mr. Smith retrieves his students&#8217; results from his online multiple-choice exams. The only change would be the answers in <code>exam_format</code> for any future exams.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">exam_format = {1: 'B', 2: 'E', 3: 'C', 4: 'D', 5: 'D'}
q4_exam = {**exam_format}

students = {'Amy': {1: 'B', 2: 'E', 3: 'C', 4: 'B', 5: 'D'},
            'Ben': {1: 'C', 2: 'E', 3: 'A', 4: 'D', 5: 'D'},
            'Joe': {1: 'E', 2: 'C', 3: 'A', 4: 'B', 5: 'D'}}

for s_name, s_answers in students.items():
    correct = 0

    for s_num in s_answers:
        for exam_q in exam_format:
            if (s_num == exam_q) and (s_answers[s_num] == exam_format[exam_q]):
                correct += 1
    print(s_name, correct)</pre>



<p></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Summary</h2>



<p>This article has provided seven (7) ways to copy a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> to select the best fit for your coding requirements.</p>



<p>Good Luck &amp; Happy Coding!</p>



<hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio"/>



<p></p>



<p></p>



<p></p>



<p></p>
<p>The post <a href="https://blog.finxter.com/7-ways-to-copy-a-dictionary-in-python/">7 Pythonic Ways to Copy a Dictionary</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Export MySQL to a CSV (Dashboard+Python)</title>
		<link>https://blog.finxter.com/how-to-export-mysql-to-a-csv-dashboardpython/</link>
		
		<dc:creator><![CDATA[Kat McKelvie]]></dc:creator>
		<pubDate>Wed, 16 Nov 2022 00:06:48 +0000</pubDate>
				<category><![CDATA[CSV]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=890369</guid>

					<description><![CDATA[<p>This article shows you how to export a Database Table to a CSV file using MySQL. ℹ️ SQL, an acronym for Structured Query Language, is the language of the Database! This standardized language is used to manage databases, tables and the data they hold. A must-have in the coding world. This language allows coders to ... <a title="How to Export MySQL to a CSV (Dashboard+Python)" class="read-more" href="https://blog.finxter.com/how-to-export-mysql-to-a-csv-dashboardpython/" aria-label="Read more about How to Export MySQL to a CSV (Dashboard+Python)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-export-mysql-to-a-csv-dashboardpython/">How to Export MySQL to a CSV (Dashboard+Python)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">This article shows you how to export a Database Table to a CSV file using MySQL.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" />  SQL, an acronym for <strong>S</strong>tructured <strong>Q</strong>uery <strong>L</strong>anguage, is the language of the Database! This standardized language is used to manage databases, tables and the data they hold. A must-have in the coding world.<br><br>This language allows coders to select a database, a table, query data, export data and much more! The possibilities are endless! This language can be called within <code><a rel="noreferrer noopener" href="https://www.phpmyadmin.net/docs/" data-type="URL" data-id="https://www.phpmyadmin.net/docs/" target="_blank">phpMyAdmin</a></code> or directly from a Python script.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4d6.png" alt="📖" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Story</strong>: <em>Let&#8217;s say you have taken over for Sven, the IT Manager at Ignite: a used car dealership in Medford, Oregon. Ignite wants the details of all cars in their inventory. They have asked you to export this data from their server into a CSV file. How can you accomplish this? Follow along with our article to discover how!</em></p>



<p class="has-global-color-8-background-color has-background">This article assumes you have <code><a rel="noreferrer noopener" href="https://www.phpmyadmin.net/docs/" data-type="URL" data-id="https://www.phpmyadmin.net/docs/" target="_blank">phpMyAdmin</a></code> installed and a database and table to work with.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ol type="video" class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-list">
<li>Overview</li>



<li>Use <strong>phpMyAdmin</strong> and Export Tab</li>



<li>Use <strong>phpMyAdmin</strong> and the SQL Tab</li>



<li>Use <a rel="noreferrer noopener" href="https://dev.mysql.com/doc/connector-python/en/" data-type="URL" data-id="https://dev.mysql.com/doc/connector-python/en/" target="_blank"><code>mysql.connector</code></a></li>



<li>Use <a href="https://pymysql.readthedocs.io/en/latest/" data-type="URL" data-id="https://pymysql.readthedocs.io/en/latest/" target="_blank" rel="noreferrer noopener"><code>pymysql</code></a></li>
</ol>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Overview</h2>



<p>Before you export the data, let&#8217;s look at how and where this data is stored. As you can see from the image below, this data is being held, for this example, in the <code>inventory</code> table of the <code>ignite_db</code> database in phpMyAdmin.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <code><a rel="noreferrer noopener" href="https://www.phpmyadmin.net/docs/" data-type="URL" data-id="https://www.phpmyadmin.net/docs/" target="_blank">phpMyAdmin</a></code> is a 3rd party tool that manages databases, tables and the data within. It is used in administering MySQL across the web, is free to use, and can be <a rel="noreferrer noopener" href="https://www.phpmyadmin.net/docs/" data-type="URL" data-id="https://www.phpmyadmin.net/docs/" target="_blank">installed</a> locally.  Upon installation, keep the URL and login credentials handy, as they will be needed later.</p>



<p>If you have phpMyAdmin installed, navigate to and log in. From the home page, click to select the <code>ignite_db</code> database. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="368" src="https://blog.finxter.com/wp-content/uploads/2022/11/mysql-001a-1024x368.png" alt="" class="wp-image-892358" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/mysql-001a-1024x368.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/mysql-001a-300x108.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/mysql-001a-768x276.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/mysql-001a.png 1096w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>With <code>ignite_db</code> selected, click the Browse hyperlink on the right-hand side.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="213" src="https://blog.finxter.com/wp-content/uploads/2022/11/local-001-1024x213.png" alt="" class="wp-image-892786" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/local-001-1024x213.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/local-001-300x62.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/local-001-768x160.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/local-001.png 1194w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>This action opens and populates the grid to display rows of data from the <code>inventory</code> table. These results will be paginated if the table contains more than 25 rows.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="716" src="https://blog.finxter.com/wp-content/uploads/2022/11/local-002-1024x716.png" alt="" class="wp-image-892795" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/local-002-1024x716.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/local-002-300x210.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/local-002-768x537.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/local-002.png 1097w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: By default, the number of rows/page is 25. Click the Number of rows dropdown to modify.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Use phpMyAdmin and Export Tab</h2>



<p class="has-global-color-8-background-color has-background">The data from the <code>inventory</code> table can be exported into a CSV file directly from phpMyAdmin using the Export Tab. You can&#8217;t see it from the interface; however, this uses MySQL to extract the data from the <code>inventory</code> table.</p>



<p>From phpMyAdmin, click the Export Tab.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="525" src="https://blog.finxter.com/wp-content/uploads/2022/11/local-003-1024x525.png" alt="" class="wp-image-892799" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/local-003-1024x525.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/local-003-300x154.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/local-003-768x393.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/local-003.png 1095w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Click the Format dropdown box to display a list of available file types. For this example, select CSV to export the data as a CSV file.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="525" src="https://blog.finxter.com/wp-content/uploads/2022/11/local-004-1024x525.png" alt="" class="wp-image-892806" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/local-004-1024x525.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/local-004-300x154.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/local-004-768x393.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/local-004.png 1095w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Click the Go button to execute. This action displays the Save As dialogue box. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="924" height="523" src="https://blog.finxter.com/wp-content/uploads/2022/11/local-005.png" alt="" class="wp-image-892810" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/local-005.png 924w, https://blog.finxter.com/wp-content/uploads/2022/11/local-005-300x170.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/local-005-768x435.png 768w" sizes="auto, (max-width: 924px) 100vw, 924px" /></figure>
</div>


<p>Select a location and file name from this dialogue box, or accept the default values. Click the Save button to complete this task. </p>



<p>For this example, this file was saved as <code>inventory.csv</code> to the desktop. When opened, the data from the <code>inventory</code> table displays (snippet of actual file).</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="852" height="492" src="https://blog.finxter.com/wp-content/uploads/2022/11/local-007.png" alt="" class="wp-image-892818" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/local-007.png 852w, https://blog.finxter.com/wp-content/uploads/2022/11/local-007-300x173.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/local-007-768x443.png 768w" sizes="auto, (max-width: 852px) 100vw, 852px" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Use phpMyAdmin and the SQL Tab</h2>



<p class="has-global-color-8-background-color has-background">What happens if you want to use phpMyAdmin and export a filtered result? You can accomplish this by using the SQL Tab and running a MySQL query.</p>



<p>From phpMyAdmin, click the SQL Tab. By default, a query is already started for you. Clear the contents. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="327" src="https://blog.finxter.com/wp-content/uploads/2022/11/local-008a-1024x327.png" alt="" class="wp-image-892828" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/local-008a-1024x327.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/local-008a-300x96.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/local-008a-768x246.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/local-008a.png 1351w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Enter the query shown below, which asks the question&#8230;<br><em>Give me all records in the inventory table where the car&#8217;s MPG is greater than 40. </em></p>



<pre class="wp-block-preformatted"><code>SELECT * FROM inventory WHERE MPG > 40</code></pre>



<p>When creating a query, to select a Column name, double-click the desired name in the Columns list or manually enter it. Once the query is complete, click the Go button to execute.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="342" src="https://blog.finxter.com/wp-content/uploads/2022/11/local-009-1024x342.png" alt="" class="wp-image-892832" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/local-009-1024x342.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/local-009-300x100.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/local-009-768x257.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/local-009-1536x513.png 1536w, https://blog.finxter.com/wp-content/uploads/2022/11/local-009.png 1547w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>This query results in the following output of nine (9) records.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="558" src="https://blog.finxter.com/wp-content/uploads/2022/11/local-010-1024x558.png" alt="" class="wp-image-892840" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/local-010-1024x558.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/local-010-300x164.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/local-010-768x419.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/local-010.png 1099w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>To export these results, scroll down the page until you see the Export hyperlink. Click this hyperlink.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="629" src="https://blog.finxter.com/wp-content/uploads/2022/11/local-011-1024x629.png" alt="" class="wp-image-892843" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/local-011-1024x629.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/local-011-300x184.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/local-011-768x472.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/local-011.png 1097w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>This action forwards you to the Export Tab (outlined earlier). Complete the same steps above to export the filtered data to a CSV file.</p>



<p>If successful, the exported CSV file, <code>inventory_filtered.csv</code>, should now contain the data shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="821" height="432" src="https://blog.finxter.com/wp-content/uploads/2022/11/local-012a.png" alt="" class="wp-image-892850" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/local-012a.png 821w, https://blog.finxter.com/wp-content/uploads/2022/11/local-012a-300x158.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/local-012a-768x404.png 768w" sizes="auto, (max-width: 821px) 100vw, 821px" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Use mysql.connector</h2>



<p class="has-global-color-8-background-color has-background">This section shows you how to filter and export data from a MySQL database to a CSV file using <a rel="noreferrer noopener" href="https://dev.mysql.com/doc/connector-python/en/" target="_blank"><code>mysql.connector</code></a> and Python.</p>



<p>Before we start, two (2) libraries require installation:</p>



<ul class="wp-block-list">
<li>The <a rel="noreferrer noopener" href="https://dev.mysql.com/doc/connector-python/en/" target="_blank"><code>mysql.connector</code></a> library which allows access to the database and table created earlier.</li>



<li>The <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="URL" data-id="https://blog.finxter.com/pandas-quickstart/" target="_blank">pandas</a> library which allows access to the CSV writer.</li>
</ul>



<p>Navigate to an IDE and run the following code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install mysql.connector
pip install pandas</pre>



<p>Next, copy and paste the code below into a blank Python file, modify the credentials, and save. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="7-11,13-15,17-22" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import mysql.connector
from mysql.connector import errorcode
import csv

mpg_hdr = ['Cars', 'MPG', 'Cylinders']

try:
    con = mysql.connector.connect(user='root', password='', host='127.0.0.1', database='ignite_db')
except mysql.connector.Error as err:
    print(err)
    exit()

cursor = con.cursor()
mpg_query = ('SELECT Car, MPG, Cylinders FROM inventory WHERE MPG > 40')
cursor.execute(mpg_query)

with open('filtered.csv', 'w', newline='') as fp:
    writer = csv.writer(fp)
    writer.writerow(mpg_hdr)

    for (Car, MPG, Cylinders) in cursor:
        writer.writerow([Car, MPG, Cylinders])

con.close()</pre>



<p><strong>Import Libraries</strong></p>



<p>The first three (3) lines in the above code snippet import the libraries and functions required to successfully run this code.</p>



<p><strong>Declare Variable</strong></p>



<p>This line creates a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a> containing the three (3) column names to be used as the header row for the CSV file. The results save to the variable <code>mpg_hdr</code>.</p>



<p><strong>Try/Except</strong></p>



<p>This section uses the <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="URL" data-id="https://blog.finxter.com/pandas-quickstart/" target="_blank"><code>try/except</code></a> statement to attempt to connect to <code>ignite_db</code> using the credentials passed. If an error occurs, this code falls into the <code>except</code> section where a message outputs to the terminal indicating the error, and the script ends.</p>



<pre class="wp-block-preformatted"><code>1044 (42000): Access denied for user ''@'localhost' to database 'ignite_db'</code></pre>



<p>If successful, the script continues.</p>



<p><strong>Create a Cursor</strong></p>



<p>The first line in this section creates a <a rel="noreferrer noopener" href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor.html" data-type="URL" data-id="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor.html" target="_blank"><code>cursor()</code></a> class. This allows the code to execute queries against the <code>ignite_db</code> database and/or the <code>inventory</code> table. The following line creates this query, saves it to <code>mpg_query</code>, and executes it on the next line.</p>



<p><strong>Write Results to CSV</strong></p>



<p>This section opens a file in write (<code>w</code>) mode and saves this as a File Object, <code>fp</code>. The File Object allows access to the <code>filtered.csv</code> file. If <code>fp</code> was output to the terminal, an Object similar to the one below displays.</p>



<pre class="wp-block-preformatted"><code>&lt;_io.TextIOWrapper name='filtered.csv' mode='w' encoding='utf8'></code></pre>



<p>Next, the header columns for the CSV file are written to this file using the <code>mpg_hdr</code> variable. Then a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> loop is instantiated to iterate through each query result, format the row data, and append it as a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>list</code></a> to the CSV file. </p>



<p>Once complete, the connection is closed and the script ends.</p>



<p><strong>Output</strong></p>



<p>If successful, the <code>filtered.csv</code> file resides in the current working directory containing the following query results.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2022/11/finished_01.png" alt="" class="wp-image-893119" width="514" height="356" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/finished_01.png 631w, https://blog.finxter.com/wp-content/uploads/2022/11/finished_01-300x208.png 300w" sizes="auto, (max-width: 514px) 100vw, 514px" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Use <code>pymysql</code></h2>



<p class="has-global-color-8-background-color has-background">This section shows you how to filter and export data from a MySQL database to a CSV file using <a rel="noreferrer noopener" href="https://pymysql.readthedocs.io/en/latest/" data-type="URL" data-id="https://pymysql.readthedocs.io/en/latest/" target="_blank"><code>pymysql</code></a> and Python.</p>



<p>Before we start, one (1) library requires installation:</p>



<ul class="wp-block-list">
<li>The <a rel="noreferrer noopener" href="https://pymysql.readthedocs.io/en/latest/" data-type="URL" data-id="https://pymysql.readthedocs.io/en/latest/" target="_blank"><code>pymysql</code></a> library which allows access to the database and table created earlier.</li>
</ul>



<p>Navigate to an IDE and run the following code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install pymysql</pre>



<p>Next, copy and paste the code below into a blank Python file and save.</p>



<p>Run this code to connect and export the <code>inventory</code> table as a CSV file to the current working directory. Change the details as needed.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4-6, 8-10,, 12-15" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pymysql
import csv

conn_details = {'user':'rot', 'password':'', 'host':'127.0.0.1', 'database':'ignite_db'}
conn = pymysql.connect(**conn_details)
cur = conn.cursor()

all_cars = 'SELECT * from inventory'
cur.execute(all_cars)
rows = cur.fetchall()

with open('inventory.csv', 'w', newline='') as fp:
    myFile = csv.writer(fp)
    myFile.writerows(rows)
conn.close()</pre>



<p><strong>Import Libraries</strong></p>



<p>The first two (2) lines in the above code snippet import the libraries required to successfully run this code.</p>



<p><strong>Connect &amp; Create Cursor</strong></p>



<p>The first line in this section saves the credentials needed to connect to <code>ignite_db</code>. The result saves to <code>conn_details</code>. The following line uses these credentials to connect. If successful, the result saves to <code>conn</code>. The following line creates a <a rel="noreferrer noopener" href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor.html" data-type="URL" data-id="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor.html" target="_blank"><code>cursor()</code></a> class allowing the code to execute queries against the <code>ignite_db</code> database and/or the <code>inventory</code> table.</p>



<p><strong>Execute Query</strong></p>



<p>The first line in this section declares the query, <code>all_cars</code>. The following line executes this query. Then, the next line fetches the query results and saves them to the variable <code>rows</code>.</p>



<p><strong>Write Results to CSV</strong></p>



<p>This section opens a file (<code>inventory.csv</code>) in write (<code>w</code>) mode and saves this as a File Object, <code>fp</code>. The File Object allows access to the <code>inventory.csv</code> file. If <code>fp</code> was output to the terminal, an Object similar to the one below displays.</p>



<pre class="wp-block-preformatted"><code>&lt;_io.TextIOWrapper name='inventory.csv' mode='w' encoding='cp1252'></code></pre>



<p>The following two (2) lines write the query results to <code>inventory.csv</code>, and the script ends.</p>



<p><strong>Output</strong></p>



<p>If successful, the <code>inventory.csv</code> file resides in the current working directory containing the following query results.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="853" height="496" src="https://blog.finxter.com/wp-content/uploads/2022/11/final_002.png" alt="" class="wp-image-894723" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/final_002.png 853w, https://blog.finxter.com/wp-content/uploads/2022/11/final_002-300x174.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/final_002-768x447.png 768w" sizes="auto, (max-width: 853px) 100vw, 853px" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Summary</h2>



<p>This article has shown four (4) ways to export MySQL to a CSV to select the best fit for your coding requirements.</p>



<p>Good Luck &amp; Happy Coding!</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Programmer Humor &#8211; Blockchain</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="280" height="394" src="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png" alt="" class="wp-image-457795" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png 280w, https://blog.finxter.com/wp-content/uploads/2022/07/image-31-213x300.png 213w" sizes="auto, (max-width: 280px) 100vw, 280px" /><figcaption><em>&#8220;Blockchains are like grappling hooks, in that it&#8217;s extremely cool when you encounter a problem for which they&#8217;re the right solution, but it happens way too rarely in real life.&#8221;</em> <strong>source </strong>&#8211; <a href="https://imgs.xkcd.com/comics/blockchain.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/blockchain.png" target="_blank" rel="noreferrer noopener">xkcd</a></figcaption></figure>
</div>


<p></p>



<p></p>



<p></p>
<p>The post <a href="https://blog.finxter.com/how-to-export-mysql-to-a-csv-dashboardpython/">How to Export MySQL to a CSV (Dashboard+Python)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Execute Python Shell Commands</title>
		<link>https://blog.finxter.com/how-to-execute-python-shell-commands/</link>
		
		<dc:creator><![CDATA[Kat McKelvie]]></dc:creator>
		<pubDate>Sun, 13 Nov 2022 19:12:13 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Operating System]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[Windows]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=887777</guid>

					<description><![CDATA[<p>This article shows you how to execute Python commands in the Shell. ℹ️ The Shell is known as a command-line interface because it interacts with the Operating System. In Windows, it is referred to as the Command Prompt. In Linux, the Terminal. Let&#8217;s start learning how to use the Shell! Access the Shell This section ... <a title="How to Execute Python Shell Commands" class="read-more" href="https://blog.finxter.com/how-to-execute-python-shell-commands/" aria-label="Read more about How to Execute Python Shell Commands">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-execute-python-shell-commands/">How to Execute Python Shell Commands</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">This article shows you how to execute Python commands in the Shell.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The Shell is known as a command-line interface because it interacts with the Operating System. In Windows, it is referred to as the Command Prompt. In Linux, the Terminal. </p>



<hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio"/>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Let&#8217;s start learning how to use the Shell!</p>



<ol type="video" class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-list">
<li>Access the Shell</li>



<li>Close the Shell</li>



<li>Enter and Run Python Commands from the Shell</li>



<li>Run a <code>.bat</code> File from the Shell using <a rel="noreferrer noopener" href="https://docs.python.org/3/library/subprocess.html" target="_blank"><code>subprocess</code></a></li>



<li>Execute Python Scripts using <a rel="noreferrer noopener" href="https://blog.finxter.com/exploring-pythons-os-module/" data-type="URL" data-id="https://blog.finxter.com/exploring-pythons-os-module/" target="_blank"><code>os.system()</code></a></li>
</ol>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Access the Shell</h2>



<p class="has-global-color-8-background-color has-background">This section shows you how to access the Shell using the <a rel="noreferrer noopener" href="https://code.visualstudio.com/" data-type="URL" data-id="https://code.visualstudio.com/" target="_blank">VSC</a> IDE.</p>



<p>Open the <a rel="noreferrer noopener" href="https://code.visualstudio.com/" data-type="URL" data-id="https://code.visualstudio.com/" target="_blank">VSC</a> IDE. Then, navigate to <code>View → Terminal</code>, or use the key combination (<code>CTRL+J</code>). </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="529" src="https://blog.finxter.com/wp-content/uploads/2022/11/shell-001-1024x529.png" alt="" class="wp-image-887824" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/shell-001-1024x529.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-001-300x155.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-001-768x397.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-001.png 1304w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Either of the above actions opens a Terminal window.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="424" src="https://blog.finxter.com/wp-content/uploads/2022/11/shell-002-1024x424.png" alt="" class="wp-image-887827" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/shell-002-1024x424.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-002-300x124.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-002-768x318.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-002.png 1319w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>To start the Shell, type <code>python</code> at the prompt (similar to below) and press the <code>&lt;Enter&gt;</code> key.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="401" src="https://blog.finxter.com/wp-content/uploads/2022/11/shell-003-1024x401.png" alt="" class="wp-image-887834" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/shell-003-1024x401.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-003-300x118.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-003-768x301.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-003.png 1319w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>The above action displays the command prompt (<code>&gt;&gt;&gt;</code>). </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="506" src="https://blog.finxter.com/wp-content/uploads/2022/11/shell-004-1024x506.png" alt="" class="wp-image-887855" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/shell-004-1024x506.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-004-300x148.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-004-768x379.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-004.png 1320w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Close the Python Shell</h2>



<p class="has-global-color-8-background-color has-background">This section touches on various ways to close the Shell and terminate code execution. </p>



<p>Below outlines the four (4) available options to perform the above task:</p>



<ol class="wp-block-list">
<li>At the command prompt (<code>>>></code>), enter the key combination <code>CTRL+Z</code> and press the <code>&lt;Enter></code> key. To terminate code execution, this is the best option.</li>



<li>At the command prompt (<code>&gt;&gt;&gt;</code>),, enter <a rel="noreferrer noopener" href="https://docs.python.org/3/library/sys.html" data-type="URL" data-id="https://docs.python.org/3/library/sys.html" target="_blank"><code>exit()</code></a> and press the <code>&lt;Enter&gt;</code> key.</li>



<li>At the command prompt (<code>>>></code>), enter <a rel="noreferrer noopener" href="https://docs.python.org/3/library/sys.html" data-type="URL" data-id="https://docs.python.org/3/library/sys.html" target="_blank"><code>quit()</code></a> and press the <code>&lt;Enter></code> key.</li>



<li>In the terminal window, click the <code>delete</code> (trashcan) icon on the right-hand side.</li>
</ol>



<p>Your IDE options may differ slightly.</p>



<p class="has-global-color-8-background-color has-background"><strong><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Note</strong>: To show/hide the Shell, click the <code>CTRL+J</code> key combination.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Enter and Run Python Code from the Shell</h2>



<p class="has-global-color-8-background-color has-background">This section shows how to run Python code directly from the Shell.</p>



<h3 class="wp-block-heading"><strong>Example 1: Perform Mathematical Operations</strong></h3>



<p>Not only can you run Python code, but you can also perform mathematical operations. From the command prompt (<code>>>></code>), enter <code>5+7</code>. Press the <code>&lt;Enter></code> key to execute.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="506" src="https://blog.finxter.com/wp-content/uploads/2022/11/shell-004-1024x506.png" alt="" class="wp-image-887855" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/shell-004-1024x506.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-004-300x148.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-004-768x379.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-004.png 1320w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>If successful, 7 is output to the terminal window.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading"><strong>Example 2: Print a String</strong></h3>



<p>This example executes Python&#8217;s <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="URL" data-id="https://blog.finxter.com/python-print/" target="_blank"><code>print()</code></a> statement. From the command prompt (<code>>>></code>), enter <code>print('The Finxter Academy')</code>. Press the <code>&lt;Enter></code> key to execute.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="506" src="https://blog.finxter.com/wp-content/uploads/2022/11/shell-100-1024x506.png" alt="" class="wp-image-888071" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/shell-100-1024x506.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-100-300x148.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-100-768x379.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-100.png 1320w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>If successful, the string inside the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="URL" data-id="https://blog.finxter.com/python-print/" target="_blank"><code>print()</code></a> statement is output to the terminal window.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="506" src="https://blog.finxter.com/wp-content/uploads/2022/11/shell-101-1024x506.png" alt="" class="wp-image-888080" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/shell-101-1024x506.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-101-300x148.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-101-768x379.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-101.png 1320w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading"><strong>Example 3: Iterate and Output Dictionary</strong> <strong>Keys</strong></h3>



<p>For this example, we have a <a href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/"><code>Dictionary</code></a> of employees saved to the variable <code>staff</code>. This code, when executed, outputs the <code>key</code> of each <a href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/"><code>Dictionary</code></a> entry to the terminal window.</p>



<p>To see this code in action, copy the code snippet below to the Windows clipboard. Navigate to the command prompt (<code>>>></code>). Then right-mouse click to paste the code from the Windows clipboard to the terminal window.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">staff = {'Amy': 55093, 'Joe': 44094, 'Sue': 3786}
for s in staff: 
   print(s)</pre>



<p>In this example, the above action displays a pop-up box.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="625" src="https://blog.finxter.com/wp-content/uploads/2022/11/shell-104-1024x625.png" alt="" class="wp-image-888121" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/shell-104-1024x625.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-104-300x183.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-104-768x469.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-104.png 1315w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>To prevent this pop-up from displaying, place a checkmark in the <strong>Do not show again</strong> checkbox. Click the Paste button to paste this code from the Windows clipboard to the terminal window. </p>



<p>Press the <code>&lt;Enter></code> key to execute.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="625" src="https://blog.finxter.com/wp-content/uploads/2022/11/shell-102-1024x625.png" alt="" class="wp-image-888110" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/shell-102-1024x625.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-102-300x183.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-102-768x469.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-102.png 1315w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h3 class="wp-block-heading"><strong>Example 4: Determine Installed Library Version</strong></h3>



<p class="has-global-color-8-background-color has-background">This section outputs the currently installed version of the <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="URL" data-id="https://blog.finxter.com/pandas-quickstart/" target="_blank">Pandas</a> library to the terminal window. This library must be <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-pandas-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-pandas-in-python/" target="_blank">installed</a> before running this code.</p>



<p>To see this code in action, copy the code snippet below to the Windows clipboard. Navigate to the command prompt (<code>&gt;&gt;&gt;</code>). Right-mouse click to paste the code from the Windows clipboard to the terminal window.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas
pandas.__version__</pre>



<p>Press the <code>&lt;Enter></code> key to execute.</p>



<p>If successful, the currently installed version of the <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="URL" data-id="https://blog.finxter.com/pandas-quickstart/" target="_blank">Pandas</a> library is output to the terminal window.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="533" src="https://blog.finxter.com/wp-content/uploads/2022/11/shell-106-1024x533.png" alt="" class="wp-image-888235" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/shell-106-1024x533.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-106-300x156.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-106-768x400.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-106.png 1323w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Run a Batch (.bat) File from the Shell using subprocess()</h2>



<p class="has-global-color-8-background-color has-background">This section shows how to execute a <code>.bat</code> script from the Shell using a <a rel="noreferrer noopener" href="https://docs.python.org/3/library/subprocess.html" target="_blank"><code>subprocess</code></a>.</p>



<p>For this example, a <code>.bat</code> (batch) file will be created and ran from the Shell. </p>



<p>First, create a Python file called <code>counter.py</code>. Copy and paste the contents of the code snippet below into this file and save it.</p>



<p>This code iterates through a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>while</code></a> loop and outputs a string with the value of <code>lift_off</code> on each iteration and pauses for two (2) seconds. This continues until the value of <code>lift_off</code> is greater than zero (0).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from datetime import datetime
from time import sleep

lift_off = 5

while lift_off > 0:
    print (f'Lift Off in {lift_off} seconds!')
    sleep(2)
    lift_off -= 1</pre>



<p>Next, create a file called <code>counter.bat</code>. Copy and paste the contents of the code snippet below into this file and save it. The first line hides any output (except for that in the <code>counter.py</code> file). </p>



<ul class="wp-block-list">
<li>The first argument on the following line is the full path to <code>python.exe</code>. </li>



<li>The second argument is the full path to the <code><a href="https://blog.finxter.com/how-to-schedule-a-batch-python-script/" data-type="post" data-id="880057" target="_blank" rel="noreferrer noopener">.bat</a></code> file. </li>
</ul>



<p>Modify as needed.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@echo off
"C:\Python\python.exe" "C:\PYTHON_CODE\counter.py"</pre>



<p>Next, navigate to the command prompt (<code>&gt;&gt;&gt;</code>). Copy and paste the contents of the code snippet below to the terminal window. This snippet imports the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/subprocess.html" target="_blank"><code>subprocess</code></a> library and passes the full path of the <code>.bat</code> file as an argument</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import subprocess
subprocess.call([r'C:\\PYTHON_CODE\\P_TRAINING\\LEARN\\CHRIS\WORK\\counter.bat'])</pre>



<p class="has-contrast-color has-base-background-color has-text-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Python&#8217;s <a rel="noreferrer noopener" href="https://docs.python.org/3/library/subprocess.html" data-type="URL" data-id="https://docs.python.org/3/library/subprocess.html" target="_blank"><code>subprocess</code></a> library runs applications by creating a process. This allows an application to execute by passing it as an argument, such as a <code>.bat</code> file or another application.</p>



<p>Press the <code>&lt;Enter></code> key to execute.</p>



<p>If successful, the following output displays.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="624" src="https://blog.finxter.com/wp-content/uploads/2022/11/shell-107-1024x624.png" alt="" class="wp-image-888310" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/shell-107-1024x624.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-107-300x183.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-107-768x468.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/shell-107.png 1320w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Execute Commands using os</h2>



<p class="has-global-color-8-background-color has-background">This section shows how to execute Python code using the <a rel="noreferrer noopener" href="https://blog.finxter.com/exploring-pythons-os-module/" target="_blank"><code>os</code></a> library.</p>



<p>To execute this code, navigate to the command prompt (<code>&gt;&gt;&gt;</code>). Copy and paste the code snippet below into the terminal window.</p>



<p>This code imports the <a rel="noreferrer noopener" href="https://blog.finxter.com/exploring-pythons-os-module/" target="_blank"><code>os</code></a> library and calls the <a rel="noreferrer noopener" href="https://blog.finxter.com/exploring-pythons-os-module/" data-type="URL" data-id="https://blog.finxter.com/exploring-pythons-os-module/" target="_blank"><code>os.system()</code></a> function. This calls and executes the <code>counter.py</code> file.</p>



<pre class="wp-block-preformatted"><code>import os
os.system("python counter.py")</code></pre>



<p>Press the <code>&lt;Enter></code> key to execute.</p>



<p>If successful, the following output displays.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="624" src="https://blog.finxter.com/wp-content/uploads/2022/11/cls-003-1024x624.png" alt="" class="wp-image-890033" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/cls-003-1024x624.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/11/cls-003-300x183.png 300w, https://blog.finxter.com/wp-content/uploads/2022/11/cls-003-768x468.png 768w, https://blog.finxter.com/wp-content/uploads/2022/11/cls-003.png 1320w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Summary</h2>



<p>This article has shown you how to work with the Shell in Python. To learn more about the Shell, click <a rel="noreferrer noopener" href="https://readthedocs.org/projects/shell-command/" data-type="URL" data-id="https://readthedocs.org/projects/shell-command/" target="_blank">here</a>.</p>



<p>Good Luck &amp; Happy Coding!</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Programming Humor</h2>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science.</p>



<p>~~~</p>



<ul class="has-global-color-8-background-color has-background wp-block-list"><li><strong>Question</strong>: Why do Java programmers wear glasses?</li><li><strong>Answer</strong>: Because they cannot C# &#8230;!</li></ul>



<p>Feel free to check out <a href="https://blog.finxter.com/what-is-the-geekiest-joke/" data-type="post" data-id="617" target="_blank" rel="noreferrer noopener">our blog article</a> with more coding jokes. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://blog.finxter.com/how-to-execute-python-shell-commands/">How to Execute Python Shell Commands</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Parsing XML Files in Python &#8211; 4 Simple Ways</title>
		<link>https://blog.finxter.com/parsing-xml-files-in-python-a-simple-guide/</link>
		
		<dc:creator><![CDATA[Kat McKelvie]]></dc:creator>
		<pubDate>Sat, 12 Nov 2022 14:05:43 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[XML]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=883225</guid>

					<description><![CDATA[<p>Problem Formulation and Solution Overview This article will show you various ways to work with an XML file. ℹ️ XML is an acronym for Extensible Markup Language. This file type is similar to HTML. However, XML does not have pre-defined tags like HTML. Instead, a coder can define their own tags to meet specific requirements. ... <a title="Parsing XML Files in Python &#8211; 4 Simple Ways" class="read-more" href="https://blog.finxter.com/parsing-xml-files-in-python-a-simple-guide/" aria-label="Read more about Parsing XML Files in Python &#8211; 4 Simple Ways">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/parsing-xml-files-in-python-a-simple-guide/">Parsing XML Files in Python &#8211; 4 Simple Ways</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio wp-block-heading">Problem Formulation and Solution Overview</h2>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">This article will show you various ways to work with an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> file.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> is an acronym for E<strong>x</strong>tensible <strong>M</strong>arkup <strong>L</strong>anguage. This file type is similar to HTML. However, <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"></a><a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> does not have pre-defined tags like HTML. Instead, a coder can define their own tags to meet specific requirements.  <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"></a><a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> is a great way to transmit and share data, either locally or via the internet. This file can be parsed based on standardized <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"></a><a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> if structured correctly.</p>



<p>To make it more interesting, we have the following running scenario:</p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Jan, a Bookstore Owner, wants to know the top three (3) selling Books in her store. This data is currently saved in an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> format. </p>



<hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio"/>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4ac.png" alt="💬" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write code to read in and extract data from an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank">XML</a> file into a Python script<em>?</em></p>



<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this by performing the following steps:</p>



<ul class="wp-block-list">
<li><strong>Method 1</strong>: Use <a rel="noreferrer noopener" href="https://pypi.org/project/xmltodict/" data-type="URL" data-id="https://pypi.org/project/xmltodict/" target="_blank"><code>xmltodict()</code></a> </li>



<li><strong>Method 2</strong>: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/xml.dom.minidom.html" target="_blank"><code>minidom.parse()</code></a></li>



<li><strong>Method 3</strong>: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/xml.etree.elementtree.html" data-type="URL" data-id="https://docs.python.org/3/library/xml.etree.elementtree.html" target="_blank"><code>etree</code></a></li>



<li><strong>Method 4:</strong> Use <a rel="noreferrer noopener" href="https://pypi.org/project/untangle/" data-type="URL" data-id="https://pypi.org/project/untangle/" target="_blank"><code>untangle.parse()</code></a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 1: Use xmltodict()</h2>



<p class="has-global-color-8-background-color has-background">This method uses the <a rel="noreferrer noopener" href="https://pypi.org/project/xmltodict/" data-type="URL" data-id="https://pypi.org/project/xmltodict/" target="_blank"><code>xmltodict()</code></a> function to read an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> file, convert it to a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank"><code>Dictionary</code></a> and extract the data.</p>



<p>In the current working directory, create an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> file called <code>books.xml</code>. Copy and paste the code snippet below into this file and save it.</p>



<pre class="wp-block-preformatted"><code>&lt;bookstore&gt;
    &lt;book&gt;
        &lt;title&gt;Surrender&lt;/title&gt;
        &lt;author&gt;Bono&lt;/author&gt;
        &lt;sales&gt;21987&lt;/sales&gt;
    &lt;/book&gt;
    &lt;book&gt;
        &lt;title&gt;Going Rogue&lt;/title&gt;
        &lt;author&gt;Janet Evanovich&lt;/author&gt;
        &lt;sales&gt;15986&lt;/sales&gt;
    &lt;/book&gt;
    &lt;book&gt;
        &lt;title&gt;Triple Cross&lt;/title&gt;
        &lt;author&gt;James Patterson&lt;/author&gt;
        &lt;sales&gt;11311&lt;/sales&gt;
    &lt;/book&gt;
&lt;/bookstore&gt;</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>In the current working directory, create a Python file called <code>books.py</code>. Copy and paste the code snippet below into this file and save it. This code reads in and parses the above <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> file. If necessary, <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-xmltodict-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-xmltodict-in-python/" target="_blank">install</a> the <a rel="noreferrer noopener" href="https://pypi.org/project/xmltodict/" data-type="URL" data-id="https://pypi.org/project/xmltodict/" target="_blank"><code>xmltodict</code></a> library.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-5, 7-10" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import xmltodict

with open('books.xml', 'r') as fp:
    books_dict =  xmltodict.parse(fp.read())
    fp.close()

for i in books_dict:
    for j in books_dict[i]:
        for k in books_dict[i][j]:
            print(f'Title: {k["title"]} \t Sales: {k["sales"]}')</pre>



<p>The first line in the above code snippet imports the <a rel="noreferrer noopener" href="https://pypi.org/project/xmltodict/" data-type="URL" data-id="https://pypi.org/project/xmltodict/" target="_blank"><code>xmltodict</code></a> library. This library is needed to access and parse the <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> file.</p>



<p>The following highlighted section opens <code>books.xml</code> in read mode (<code>r</code>) and saves it as a File Object, fp. If fp was output to the terminal, an object similar to the one below would display.</p>



<pre class="wp-block-preformatted"><code>&lt;_io.TextIOWrapper name='books.xml' mode='r' encoding='cp1252'&gt;</code></pre>



<p>Next, the <a href="https://pypi.org/project/xmltodict/" data-type="URL" data-id="https://pypi.org/project/xmltodict/"><code>xmltodict.parse()</code></a> function is called and passed one (1) argument, <a rel="noreferrer noopener" href="https://blog.finxter.com/5-ways-to-read-a-text-file-from-a-url/" data-type="URL" data-id="https://blog.finxter.com/5-ways-to-read-a-text-file-from-a-url/" target="_blank"><code>fp.read()</code></a>, which reads in and parses the contents of the <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> file. The results save to <code>books_dict</code> as a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank"><code>Dictionary</code></a>, and the file is closed. The contents of <code>books_dict</code> are shown below.</p>



<pre class="wp-block-preformatted"><code>{'bookstore': 
  {'book': [{'title': Surrender', 'author': 'Bono', 'sales': '21987'}, 
              {'title': 'Going Rogue', 'author': 'Janet Evanovich', 'sales': '15986'}, 
              {'title': 'Triple Cross', 'author': 'James Patterson', 'sales': '11311'}]}}</code></pre>



<p>The final highlighted section loops through the above <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank"><code>Dictionary</code></a> and extracts each book&#8217;s <code>Title</code> and <code>Sales</code>.</p>



<pre class="wp-block-preformatted"><code>Title: Surrender         Sales: 21987
Title: Going Rogue    Sales: 15986
Title: Triple Cross      Sales: 11311</code></pre>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: The <code>\t</code> character represents the &lt;Tab&gt; key on the keyboard.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Dictionary – The Ultimate Guide" width="937" height="527" src="https://www.youtube.com/embed/qX0qqEVpP5s?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 2: Use minidom.parse()</h2>



<p class="has-global-color-8-background-color has-background">This method uses the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/xml.dom.minidom.html" data-type="URL" data-id="https://docs.python.org/3/library/xml.dom.minidom.html" target="_blank"><code>minidom.parse()</code></a> function to read and parse an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank">XML</a> file. This example extracts the ID, Title and Sales for each book.</p>



<p>This example differs from Method 1 as this <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> file contains an additional line at the top (<code>&lt;?xml version="1.0"?&gt;</code>) of the file and each <code>&lt;book&gt;</code> tag now has an <code>id</code> (attribute) assigned to it. </p>



<p>In the current working directory, create an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> file called <code>books2.xml</code>. Copy and paste the code snippet below into this file and save it.</p>



<pre class="wp-block-preformatted"><code>&lt;?xml version="1.0"?&gt;
&lt;bookstore&gt;
	&lt;storename&gt;Jan's Best Sellers List&lt;/storename&gt;
	&lt;book id="21237"&gt;
		&lt;title&gt;Surrender&lt;/title&gt;
                &lt;author&gt;Bono&lt;/author&gt;
		&lt;sales&gt;21987&lt;/sales&gt;
	&lt;/book&gt;
	&lt;book id="21946"&gt;
		&lt;title&gt;Going Rogue&lt;/title&gt;
                &lt;author&gt;Janet Evanovich&lt;/author&gt;
		&lt;sales&gt;15986&lt;/sales&gt;
	&lt;/book&gt;
	&lt;book id="18241"&gt;
		&lt;title&gt;Triple Cross&lt;/title&gt;
                &lt;author&gt;James Patterson&lt;/author&gt;
		&lt;sales&gt;11311&lt;/sales&gt;
	&lt;/book&gt;
&lt;/bookstore&gt;</code></pre>



<p>In the current working directory, create a Python file called <code>books2.py</code>. Copy and paste the code snippet below into this file and save it. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-5, 7-13" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from xml.dom import minidom

doc = minidom.parse('books2.xml')
name = doc.getElementsByTagName('storename')[0]
books = doc.getElementsByTagName('book')

for b in books:
        bid    = b.getAttribute('id')
        title  = b.getElementsByTagName('title')[0]
        sales  = b.getElementsByTagName('sales')[0]
        print(f'{bid} {title.firstChild.data} {sales.firstChild.data}')</pre>



<p>The first line in the above code snippet imports the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/xml.dom.minidom.html" data-type="URL" data-id="https://docs.python.org/3/library/xml.dom.minidom.html" target="_blank"><code>minidom</code></a> library. This allows access to various functions to parse the <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> file and retrieve tags and attributes.</p>



<p>The first section of highlighted lines performs the following:</p>



<ul class="wp-block-list">
<li>Reads and parse the <code>books2.xml</code> file and saves the results to <code>doc</code>. This action creates the Object shown as (1) below.</li>



<li>Retrieves the <code>&lt;storename&gt;</code> tag and saves the results to <code>name</code>. This action creates an Object shown as (2) below.</li>



<li>Retrieves the <code>&lt;book&gt;</code> tag for each <code>book</code> and saves the results to <code>books</code>. This action creates a List of three (3) Objects: one for each book shown as (3) below.</li>
</ul>



<pre class="wp-block-preformatted"><code>(1) &lt;xml.dom.minidom.Document object at 0x0000022D764AFEE0&gt; 
(2) &lt;DOM Element: storename at 0x22d764f0ee0&gt; 
(3) [&lt;DOM Element: book at 0x22d764f3a30&gt;, 
&lt;DOM Element: book at 0x22d764f3c70&gt;, 
&lt;DOM Element: book at 0x22d764f3eb0&gt;]</code></pre>



<p>The last section of highlighted lines loop through the books Object and outputs the results to the terminal.</p>



<pre class="wp-block-preformatted"><code>21237 Surrender 21987
21946 Going Rogue 15986
18241 Triple Cross 11311</code></pre>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python getattr() - Ultimate Guide" width="937" height="527" src="https://www.youtube.com/embed/5MXDZI3jRio?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 3: Use etree</h2>



<p class="has-global-color-8-background-color has-background">This method uses <a rel="noreferrer noopener" href="https://docs.python.org/3/library/xml.etree.elementtree.html" data-type="URL" data-id="https://docs.python.org/3/library/xml.etree.elementtree.html" target="_blank"><code>etree</code></a> to read in and parses an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank">XML</a> file. This example extracts the Title and Sales data for each book.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The <code>etree</code> considers the <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank">XML</a> file as a tree structure. Each element represents a node of said tree. Accessing elements is done on an element level.</p>



<p>This example reads in and parses the <code>books2.xml</code> file created earlier.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3,4, 6-10" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import xml.etree.ElementTree as ET

xml_data = ET.parse('books2.xml')
root = xml_data.getroot()

for books in root.findall('book'):
    title = books.find('title').text
    author = books.find('author').text
    sales = books.find('sales').text
    print(title, author, sales)</pre>



<p>The first line in the above code snippet imports the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/xml.etree.elementtree.html" data-type="URL" data-id="https://docs.python.org/3/library/xml.etree.elementtree.html" target="_blank"><code>etree</code></a> library. This allows access to all nodes of the <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank">XML</a> <code>&lt;tag&gt;</code> structure.</p>



<p>The following line reads in and parses <code>books2.xml</code>. The results save as an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank">XML</a> Object to <code>xml_data</code>. If output to the terminal, an Object similar to the one below displays.</p>



<pre class="wp-block-preformatted"><code>&lt;Element 'bookstore' at 0x000001E45E9442C0&gt;</code></pre>



<p>The following highlighted section uses a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> loop to iterate through each <code>&lt;book&gt;</code> tag, extracting the <code>&lt;title&gt;</code>, <code>&lt;author&gt;</code> and <code>&lt;sales&gt;</code> tags for each book and outputting them to the terminal.</p>



<pre class="wp-block-preformatted"><code>Surrender Bono 21987
Going Rogue Janet Evanovich 15986
Triple Cross James Patterson 11311</code></pre>



<p>To retrieve the attribute of the <code>&lt;book&gt;</code> tag, run the following code.</p>



<p>This code extracts the <code>id</code> attribute from each <code>&lt;book&gt;</code> tag and outputs it to the terminal.</p>



<pre class="wp-block-preformatted"><code>{'id': '21237'}
{'id': '21946'}
{'id': '18241'}</code></pre>



<p>To extract the values, run the following code.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for id in root.iter('book'):
    vals = id.attrib.values()
    for v in vals:
        print(vals)</pre>



<pre class="wp-block-preformatted"><code>21237
21946
18241</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Method 4: Use untangle.parse()</h2>



<p class="has-global-color-8-background-color has-background">This method uses <a rel="noreferrer noopener" href="https://pypi.org/project/untangle/" data-type="URL" data-id="https://pypi.org/project/untangle/" target="_blank"><code>untangle.parse()</code></a> to parse an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank">XML</a> string.</p>



<p>This example reads in and parses the <code>books3.xml</code> file shown below. If necessary, install the <a rel="noreferrer noopener" href="https://pypi.org/project/untangle/" data-type="URL" data-id="https://pypi.org/project/untangle/" target="_blank"><code>untangle</code></a> library.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" /> The <a rel="noreferrer noopener" href="https://pypi.org/project/untangle/" data-type="URL" data-id="https://pypi.org/project/untangle/" target="_blank"><code>untangle</code></a> library converts an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank">XML</a> file to a Python object. This is a good option when you have a group of items, such as book names.</p>



<p>In the current working directory, create an <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> file called <code>books3.xml</code>. Copy and paste the code snippet below into this file and save it. If necessary, <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-xmltodict-in-python/" target="_blank">install</a> the <a href="https://pypi.org/project/untangle/" data-type="URL" data-id="https://pypi.org/project/untangle/" target="_blank" rel="noreferrer noopener"><code>untangle</code></a> library.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0"?>
&lt;root>
    &lt;book name="Surrender"/>
    &lt;book name="Going Rogue"/>
    &lt;book name="Triple Cross"/>
&lt;/root></pre>



<p>In the current working directory, create a Python file called <code>books3.py</code>. Copy and paste the code snippet below into this file and save it. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-4,6-7" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import untangle

book_obj = untangle.parse('books3.xml')
books = ','.join([book['name'] for book in book_obj.root.book])

for b in books.split(','):
    print(b)</pre>



<p>The first line in the above code snippet imports the <a rel="noreferrer noopener" href="https://pypi.org/project/untangle/" data-type="URL" data-id="https://pypi.org/project/untangle/" target="_blank"><code>untangle</code></a> library allowing access to the <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> file structure.</p>



<p>The following line reads in and parses the <code>books3.xml</code> file. The results save to <code>book_obj</code>. </p>



<p>The next line calls the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-join/" data-type="URL" data-id="https://blog.finxter.com/python-string-join/" target="_blank"><code>join()</code></a> function and passes it one (1) argument: <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a>. This code iterates through and retrieves the name of each book and saves the results to <code>books</code>. If output to the terminal, the following displays:</p>



<pre class="wp-block-preformatted"><code> Surrender,Going Rogue,Triple Cross</code></pre>



<p>The next line instantiates a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank"><code>for</code></a> loop, iterates through each book name, and sends it to the terminal.</p>



<pre class="wp-block-preformatted"><code>Surrender
Going Rogue
Triple Cross</code></pre>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python One-Liner Trick 9 - Nested List Comprehension" width="937" height="527" src="https://www.youtube.com/embed/aBC0VhpXkOQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Summary</h2>



<p>This article has shown four (4) ways to work with <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" data-type="URL" data-id="https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction" target="_blank"><code>XML</code></a> files to select the best fit for your coding requirements.</p>



<p>Good Luck &amp; Happy Coding!</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Programmer Humor &#8211; Blockchain</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="280" height="394" src="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png" alt="" class="wp-image-457795" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png 280w, https://blog.finxter.com/wp-content/uploads/2022/07/image-31-213x300.png 213w" sizes="auto, (max-width: 280px) 100vw, 280px" /><figcaption><em>&#8220;Blockchains are like grappling hooks, in that it&#8217;s extremely cool when you encounter a problem for which they&#8217;re the right solution, but it happens way too rarely in real life.&#8221;</em> <strong>source </strong>&#8211; <a href="https://imgs.xkcd.com/comics/blockchain.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/blockchain.png" target="_blank" rel="noreferrer noopener">xkcd</a></figcaption></figure>
</div><p>The post <a href="https://blog.finxter.com/parsing-xml-files-in-python-a-simple-guide/">Parsing XML Files in Python &#8211; 4 Simple Ways</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-06-26 09:19:14 by W3 Total Cache
-->