-1

I wrote a simple function and I believe that I done it properly, but I get something wrong.

My code:

array = ['/home/sergey/Документы/008.jpeg']
save_dir = os.path.join(os.path.dirname(array[0]), "Converted_files")
os.makedirs(save_dir)

for file in array:
    if file.endswith(srcSfx):
        im = Image.open(file).convert("RGB")
        print (save_dir)
        p = os.path.join(save_dir, file[:-len(srcSfx)] + destSfx)
        print(p)
        im.save(p, destSfx)

I want to create a folder and to save some images in it. But the images are saved in the original folder, not in the 'save_dir' folder.

Printout from code:

/home/sergey/Документы/Converted_files
/home/sergey/Документы/008.png

Why does '008.png' not placed into 'save_dir'?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Instead of saying `array[0]`, provide the actual string please. Otherwise this is not reproducible. Or better yet, provide a sample of a couple of elements from `array`. – Mad Physicist Sep 09 '21 at 21:06
  • 3
    Take a closer look at `file[:-len(srcSfx)] + destSfx`. From the `join` docstring: "If any component is an absolute path, all previous path components will be discarded." – Warren Weckesser Sep 09 '21 at 21:08
  • It will be easier for someone to help you if you provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Warren Weckesser Sep 09 '21 at 21:10
  • This is the first and only element from array /home/sergey/Документы/008.jpeg – Ivan Cheshkov Sep 09 '21 at 21:10
  • @IvanCheshkov. I've added it to your question. Please do that next time for a full [mcve]. Hopefully this teaches you why you need to provide complete information, not what you think is important. After all, if you knew what was important to begin with, you probably wouldn't be asking for help. – Mad Physicist Sep 09 '21 at 21:18
  • @WarrenWeckesser. It is now. – Mad Physicist Sep 09 '21 at 21:31
  • Does https://stackoverflow.com/questions/1945920/why-doesnt-os-path-join-work-in-this-case help? – Karl Knechtel Sep 09 '21 at 21:36

1 Answers1

0

If the filenames in array are absolute paths, this will not work. join will restart the filename from an absolute path. For example, on Windows join('C:/x', 'C:/y') results in 'C:/y'. On Linux, join('/x', '/y') returns '/y'.

In your loop file[:-len(srcSfx)] + destSfx is an absolute path, so the intended prefix, save_dir is simply discarded. To avoid that, call to basename similarly to how you used dirname when constructing save_dir:

p = os.path.join(save_dir, os.path.basename(file)[:-len(srcSfx)] + destSfx)

As a minor aside, I generally prefer to import the names like

from os.path import basename, dirname, join

In that case, the result is a bit shorter and easier to read:

save_dir = join(dirname(array[0]), "Converted_files")
...
    join(save_dir, basename(file)[:-len(srcSfx)] + destSfx)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264