0

I want to import multiple images from a folder using os.path.join and os.walk. Here is the code so far:

path = '../images' # path to folder 

for _,__,image_paths in os.walk(path):
    for file_name in image_paths:
        full_path = os.path.join(path,file_name)

When I print full path I get results like

../images\00.png
../images\01.png
../images\02.png

So I got forward and backward slashes. Is that going to be a problem? I can use the paths to import images just fine but I am worried it might cause errors somewhere down the line.

I guess along with that, I see people use forward and backward slashes more or less interchangeably, is there one that should be used?

Another_coder
  • 728
  • 1
  • 9
  • 23

1 Answers1

1

It'll be fine if you're using Windows.

You can use os.path.normpath to change all the forward slashes to back slashes.

Also, if your directory structure is more than one level deep, you need to know the root directory, since it will not be the same as path if the file is in another directory. I would change your code to this:

for root, _, image_paths in os.walk(path):
    for file_name in image_paths:
        full_path = os.path.join(root, file_name)
GordonAitchJay
  • 4,640
  • 1
  • 14
  • 16
  • Thank you. Would all of that also work on macOS and Linux? – Another_coder Mar 28 '23 at 08:45
  • 2
    Of course it works on other OSs. The backslash is introduced by `os.path.join` and that will use the path separator for the respective OS. OS abstraction is the whole point of the `os` module. – Friedrich Mar 28 '23 at 08:47
  • @Another_coder yes, it all works on macOS and Linux. – GordonAitchJay Mar 28 '23 at 08:49
  • Note that on macOS and Linux, `os.path.join` would not return a string with `\` since the path separator for those systems is `/`, unlike Windows. Under the hood, Windows accepts both slashes, so there's no need to call `os.path.normpath`. Maybe if you were outputting the filepaths to the user, it would look better with only back slashes. – GordonAitchJay Mar 28 '23 at 08:53