Make path to file on Windows works on Linux

Here I have discussed troubles on working on relative path in Python.

This story is dedicate to absolute path, it describes how to make absolute Windows path (with C:\ part) work on Linux.

The source code you can found here. It is available as part of my AlexBerUtils s project.

You can install AlexBerUtils from PyPi:

python3 -m pip install -U alex-ber-utils

See here for more details explanation on how to install.

This is usage example:

Now, I recommend you to put this code snippet after you did your basic logging configuration.

You code should look like something like this:

How fix_retry_env works?

  1. This is Windows path, we’re running on Windows.
  2. This is Windows path, we’re running on POSIX.

Note: I’m using “incorrect” slash in Windows path for 2 reasons:

  • python-dotenv support only POSIX-type slashes
  • Windows works fine with “incorrect” slashes, it can successfully resolve them.

This is Windows path, we’re running on Windows.

We will correctly split our string to different paths.

For each path, we will check if it found on disk,

if found, we will leave the path unmodified.

Otherwise, we will strip out C: from the beginning of the path and we will use /app/logs/1.logs instead.

This is Windows path, we’re running on POSIX.

We will incorrectly split our string to different paths. We will get C and /app/logs/1.logs as 2 different path to iterate over.

If we have 1-letter path, we will ignore it, so C will be ignored and we will dial with /app/logs/1.logs only.

We will check if it found on disk,

if found, we will leave the path unmodified.

Otherwise, we will not found driver information in the beginning of the path, so/app/logs/1.logs will be used unmodified.

Note: If your path is on D:\ driver, algorithm above may fail. In such case it as advised to do one of the following:

  1. To use another separator instead of os.pathsep (check docstring of fix_retry_env() function how to do it).
  2. Don’t specify driver later inside path (may be Windows will correctly recognize it, I didn’t check) .
  3. To define mount without driver latter (on POSIX or inside Docker container).

Enjoy!

Senior Software Engineer at Pursway

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store