Reputation: 11
a='C:/Users/me/Documents/PythonProjects/opencv/Train\11\00011_00014_00018.png'
I am running a for loop with variables such as a, that are strings. I intend to obtain the number 11 from the string above.
Using a.replace('\\,'/')
, i get the exact same string back , that is, 'C:/Users/me/Documents/PythonProjects/opencv/Train\11\00011_00014_00018.png'
the only way i got it to work was with r/'C:/Users/me/Documents/PythonProjects/opencv/Train\11\00011_00014_00018.png'.replace('\\','/')
but that does not work with variables i.e
r'a'.replace('\\','/')
its not like f-strings whereby i can parse variables as such f'{a}'
Upvotes: 0
Views: 65
Reputation: 11
Thanks it worked !
root_dir = 'C:/Users/me/Documents/PythonProjects/opencv/Train'
all_img_paths = glob.glob(os.path.join(root_dir, '**.png'))
for img_path in all_img_paths:
try: img = preprocess_img(io.imread(img_path)) label = get_class(img_path)
to:
all_img_paths = glob.glob(os.path.join(os.path.normpath(root_dir), '**.png')) np.random.shuffle(all_img_paths)
Upvotes: 0
Reputation: 117856
I would instead recommend using os.path
if your intention is to clean up or mutate filesystem paths
>>> import os
>>> a='C:/Users/me/Documents/PythonProjects/opencv/Train\11\00011_00014_00018.png'
>>> os.path.normpath(a)
'C:\\Users\\me\\Documents\\PythonProjects\\opencv\\Train\t\x0011_00014_00018.png'
Using os.path
for path manipulation will generally behave correctly on different operating systems without you having to manually modify slashes, drive names, etc.
Upvotes: 3