skoeb
skoeb

Reputation: 885

Sanitizing file paths represented as strings across platforms in python

I work on a model which has a .csv input sheet, one of my colleagues (on windows) might save a path in this .csv input sheet such as A_Inputs\inputs\sets\modeledyears_set.csv.

Another colleague (on mac) might save a path in the .csv input sheet such as A_Inputs/inputs/sets/other_modeledyears_set.csv.

When I go to run this input sheet on our linux server, the windows entered path looks like A_Inputs\\inputs\\sets\\modeledyears_set.csv, and the mac entered path looks like A_Inputs/inputs/sets/other_modeledyears_set.csv.

Normally, I could split either path into its components and save into a universally accessible path with os.path.join(windows_path.split('\\')) or os.path.join(unix_path.split('/')),

However, I'm wondering if there is a way to get a os.path.join() result without performing both of these splits.

Is there some os function that will sanitize a path represented as a string, regardless of the direction the slashes face? I'm trying to avoid if/else logic based on the users operating system.

Upvotes: 0

Views: 723

Answers (1)

CHINTAN VADGAMA
CHINTAN VADGAMA

Reputation: 714

Instead of doing both paths, you can use the following to support both Unix and Windows

import os
os.path.join(path.split(os.pathsep))

Upvotes: 1

Related Questions