Creating Directories Safely in Python: Handling Missing Parent Paths with OSError

One approach would involve handling OSError and examining the associated error code :

import os
import errno

def create_directory(path):
   except OSError as error:
       if error.errno != errno.EEXIST:

Overall, this code snippet is a simple function that creates a directory at the specified path while handling the case where the directory already exists. It ensures that no error is raised when the directory already exists, but it will raise other errors for any unexpected issues during the directory creation process.

Alternatively, modern Python versions offer improvements to this code, introducing FileExistsError (available in Python 3.3+):

except FileExistsError:
   # The directory already exists; no need to take further action

Additionally, starting from Python 3.2, you can use the exist_ok keyword argument with os.makedirs:

os.makedirs("custom/path/to/folder", exist_ok=True)
# This will succeed even if the directory already exists.

When exist_ok is set to True, the function will not raise an exception if the specified directory already exists. Instead, it will silently complete without doing anything.

I hope it helps you!


what is DocType5 on HTML

In HTML (Hypertext Markup Language), a DOCTYPE declaration is a special line of code that appears at the very beginning of an HTML document’s source code. Its purpose is to tell web browsers and other software how to interpret and display the content of the HTML document.

Here’s a breakdown of the components of a DOCTYPE declaration:

  1. DOCTYPE: This is the keyword that signals the start of the DOCTYPE declaration.
  2. HTML version: This specifies which version of HTML the document is written in. For example, the HTML5 version is commonly used today.
  3. Public Identifier (optional): This part of the declaration identifies a formal public identifier, which is a unique string provided by an organization like the W3C (World Wide Web Consortium). It helps browsers to understand which standard to follow for rendering the HTML.
  4. System Identifier (optional): This part points to the location of a Document Type Definition (DTD) file. The DTD defines the rules and structure that the HTML document must follow. It’s used by browsers to understand how to parse and display the document.

Putting it all together, here’s an example of a DOCTYPE declaration for HTML5:

<!DOCTYPE html>

This declaration tells the browser that the document is written in HTML5. In modern web development, HTML5 is the most commonly used version of HTML.

How to evaluate distance correctly between two points in Python

Just as a note, if you just need a quick and easy way of finding the distance between two points, I strongly recommend not implementing Haversine.

You have the option to transform the numbers manually into radians, or utilize the radians functionality from the math module:

from math import sin, cos, sqrt, atan2, radians

# Approximate radius of earth in km
earth_radius_km = 6373.0
latitude1_rad = radians(43.4395755)
longitude1_rad = radians(23.2267012)
latitude2_rad = radians(47.0566784)
longitude2_rad = radians(14.5931164)

delta_longitude_rad = longitude2_rad - longitude1_rad
delta_latitude_rad = latitude2_rad - latitude1_rad

angle_a = sin(delta_latitude_rad / 2)**2 + cos(latitude1_rad) * cos(latitude2_rad) * sin(delta_longitude_rad / 2)**2
angular_distance = 2 * atan2(sqrt(angle_a), sqrt(1 - angle_a))

distance_km = earth_radius_km * angular_distance

print("Result:", distance_km)

#Result: 786.0811347907835

Here we converted latitude and longitude to radians using the radians function. The haversine formula requires angles in radians for accurate calculations.

The distance is now returning the correct value of 786 km.


How to find the 5 most occurring sublists using collections.Counter?

Hi! To count the occurrences of each sublist, you can convert them to strings by joining their elements together. Here’s an example:

L = [['', '119.222.456.130', '38673', '161', '17', '62', '4646'],
     ['16.37.456.153', '', '56388', '161', '17', '62', '4646']]

from collections import Counter

L_strings = [','.join(sublist) for sublist in L]
counter = Counter(L_strings).most_common(5)

most_frequent_elements = [item[0] for item in counter]
counts = [item[1] for item in counter]

In this code, each sublist in L is converted to a string by joining its elements using ‘,’.join(sublist). The resulting list of strings, L_strings, is then used to create a Counter object to count the occurrences.

The most_common(5) method is used to retrieve the five most frequent elements along with their counts. The variable most_frequent_elements contains the list of the most occurring sublists, while the variable counts contains the occurrence counts for each sublist.

By using this approach, you can count the occurrences of each sublist in L and retrieve the most frequent elements along with their respective counts.

How to update the Python version in Google Colab to 3.9 or above?

To update the Python version in Google Colab, you can leverage the Debian-based Linux environment provided by Colab. Similar to upgrading Python on your own Linux system, you can follow these steps:

  1. Detect the current Python version in Colab:
!python --version # Output: Python 3.8.16

      2. Install the desired Python version, such as Python 3.9:

!sudo apt-get update -y !sudo apt-get install python3.9

      3. Configure the alternatives to switch between Python versions:

!sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 1 
!sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 2

      4. Verify the Python version after the update:

!python --version 
# Output: 3.9.16

     5. To ensure the Colab kernel uses the new installed Python version, execute the following commands:

!sudo apt-get install python3.9-distutils 
!python -m pip install ipython ipython_genutils ipykernel jupyter_console prompt_toolkit httplib2 astor 
!ln -s /usr/local/lib/python3.8/dist-packages/google

     6.Remember to restart the Colab runtime after making these changes. Additionally, note that you’ll need to reinstall any packages (e.g., pandas, TensorFlow) in the new Python version. 

If you want to view a list of installed Python versions and switch between them, use the command:

!sudo update-alternatives --config python3 
# After running, enter the row number of the Python version you want.

By following these steps, you can update the Python version in Google Colab to 3.9 or above, allowing you to work with the desired Python environment.”