How To Run Multiple Python Versions On Windows?

Summary: You can run multiple versions of Python on Windows using one of the following methods: Using entire path to execute the code. Creating A Shortcut or Symbolic Link to the executable files. Using Pylauncher: Use Shebang (#) in The Script Run Pylauncher Command Using Virtual Environments. ➠ Problem Formulation: You might have two versions … Read more

Python open() Function — An 80/20 Guide By Example

Python’s built-in open() function opens a file and returns a file object. The only non-optional argument is a filename as a string of the file to be opened. You can use the file object to access the file content. For example, file_obj.readlines() reads all lines of such a file object. Here’s a minimal example of … Read more

How to Access Environment Variable Values in Python?

Problem Formulation: Say, you set an environment variable and you want to access it in your Python script. How to get the value of the environment variable? Background: Environment variables are external to the Python environment.Β  They describe the operating system environment we are using. The applications installed use this information to complete specific tasks … Read more

How to Remove a Non-Empty Folder in Python?

Problem Formulation: Given a path to a folder as a Python string. The folder is non-empty. How to remove the whole folder in your Python script? Example: Say, you have the path=’path/to/folder’ in your Python script and it contains some files and subfolders: path –to —-folder ——file1.dat ——file2.dat ——subfolder1 ——–file3.dat ——subfolder2 ——–file4.dat You want to … Read more

How to Get the Command History in Python?

If you’re working with the command line in Windows or the terminal in Linux and macOS, you know about the feature of the command-line history. You can access all previously issued commands with the arrow up or arrow down keys. As a Python coder, you want to be able to control everything from your Python … Read more

How to Increment a Filename in Python?

Challenge: Given a Python program that writes data into a file. If you run the program again, it’ll overwrite the file written by the first execution of the program. Each time you run this program, the original content in file.dat will be overwritten. How to avoid this overwriting by adding an integer suffix to the … Read more

How to Check Whether a File Exists Without Exceptions?

Challenge: Given a string ‘/path/to/file.py’. How to check whether a file exists at ‘/path/to/file.py’, without using the try and except statements for exception handling? # What You Want! if exists(‘/path/to/file.py’): … # Do something Solution: To check whether a file exists at a given path, Run from pathlib import Path to import the path object, … Read more