vitalstrike82
vitalstrike82

Reputation: 301

Glob package in Python. FIle path is append with \\ instead of /. Expecting forward slash instead of 2 backslashes

I'm using glob API to load all my CSV into a list. After executing my code, I realize the results in data_list append \ in the file path instead of / before the csv data file name.

My python code file is in this location: C:\Documents\python-workspace\analysis.py

My 4 csv data are in this location:

  1. C:\Documents\python-workspace\data\vitalstrike\user-site-export\data-1.csv

  2. C:\Documents\python-workspace\data\vitalstrike\user-site-export\data-2.csv

  3. C:\Documents\python-workspace\data\vitalstrike\user-site-export\data-3.csv

  4. C:\Documents\python-workspace\data\vitalstrike\user-site-export\data-4.csv

Below is my code to load the files into the list

import pandas as pd
import pandas_profiling
import glob

data_list = glob.glob('data/vitalstrike/user-site-export/data-*')
display(data_list)

After executing the code, I realize the results in data_list append the csv data file name with '\\' instead of '/'. Any advice how to force it to / ?

In[15]: display(data_list)
['data/vitalstrike/user-site-export\\data-1.csv',
 'data/vitalstrike/user-site-export\\data-2.csv',
 'data/vitalstrike/user-site-export\\data-3.csv']

Upvotes: 0

Views: 863

Answers (1)

Maurice Meyer
Maurice Meyer

Reputation: 18136

You could use os.path.join, to create the glob-arguments to make sure the search-pattern is using the correct OS separator (depending on the running OS):

import os
import glob

dirs = ['data', 'vitalstrike', 'user-site-export', 'data-*']
data_list = glob.glob(os.path.join(*dirs))

Output of dirs:

data/vitalstrike/user-site-export/data-*  # Mac/*nix
data\vitalstrike\user-site-export\data-*  # Windows

Upvotes: 1

Related Questions