5

I have a question about using glob in python.

I want to know why the path is showing backslashes instead of a forward slash?

Example being C:/Users/Name/Desktop/Pythonfiles\excel.xlsx

My script is

import glob
excel_list = (glob.glob("C:/Users/Name/Desktop/Pythonfiles/*.xlsx"))

This is my output I'm getting:

['C:/Users/Name/Desktop/PythonFiles\\19282.xlsx', 'C:/Users/Name/Desktop/PythonFiles\\19557.xlsx', 'C:/Users/Name/Desktop/PythonFiles\\19667.xlsx', 'C:/Users/Name/Desktop/PythonFiles\\19742.xlsx', 'C:/Users/Name/Desktop/PythonFiles\\CEImport.xlsx']

Any help would be great thank you

BPCAL
  • 85
  • 1
  • 5
  • If you use forward slash you do not need to use double slash or the [r prefix](https://stackoverflow.com/questions/19034822/unknown-python-expression-filename-r-path-to-file) – Edeki Okoh Jan 31 '20 at 20:03
  • Can you please post the full output you are receiving? – Greg Jan 31 '20 at 20:04
  • 4
    Does this answer your question? [Windows path in Python](https://stackoverflow.com/questions/2953834/windows-path-in-python) – Edeki Okoh Jan 31 '20 at 20:04
  • 1
    `glob` ultimately uses `os.path.join` to create a file path consisting of `C:/Users/Name/Desktop/Pythonfiles` and `foo.xlsx`. If `os.path.sep` is a backslash, that's what gets used, regardless of what appears in the argument. Also, the argument is only broken down into its constituent directories as necessary to isolate any "magic" characters. – chepner Jan 31 '20 at 20:05
  • @Greg This is the output I get: ['C:/Users/Name/Desktop/PythonFiles\\19282.xlsx', 'C:/Users/Name/Desktop/PythonFiles\\19557.xlsx', 'C:/Users/Name/Desktop/PythonFiles\\19667.xlsx', 'C:/Users/Name/Desktop/PythonFiles\\19742.xlsx', 'C:/Users/Name/Desktop/PythonFiles\\CEImport.xlsx'] – BPCAL Jan 31 '20 at 20:18

3 Answers3

2

\ and / are interchangeable path separators, but if you wanted to normalize the paths so they are uniform, use os.path.normpath

excel_path = [os.path.normpath(i) for i in glob.glob("C:/Users/Name/Desktop/Pythonfiles/*.xlsx")]

#output
['C:\\Users\\Name\\Desktop\\PythonFiles\\19282.xlsx',
 'C:\\Users\\Name\\Desktop\\PythonFiles\\19557.xlsx',
 'C:\\Users\\Name\\Desktop\\PythonFiles\\19667.xlsx',
 'C:\\Users\\Name\\Desktop\\PythonFiles\\19742.xlsx',
 'C:\\Users\\Name\\Desktop\\PythonFiles\\CEImport.xlsx']

dubbbdan
  • 2,650
  • 1
  • 25
  • 43
0

According to this answer here, '/' and '\' are interchangeable in python file paths.

Greg
  • 1,845
  • 2
  • 16
  • 26
0

You are probably getting the double backslashes (\\) on the string path because you are under Windows, which uses a single backslash (\) instead of a single slash (/). Please, note that \\ is the same as \, since backslash is used for especial characters.

Also, as mentioned by Greg's answer, a backslash \ and slash / are interchangeable in python file paths, thus you shouldn't worry about them.

Daniel Lima
  • 925
  • 1
  • 8
  • 22