0

I created a script in Python that insert files inside folders with the same name of the extension of the files. On Windows working fine, on Mac Os there a problem. I attach the code and error I receive.

import os
import shutil

percorso = input("Inserisci il percorso ")
os.chdir(percorso)

for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    f_new = f_ext[1:len(f_ext)]

    
    if os.path.isdir(f) or os.path.isdir('/Users/net/Downloads/.DS_Store'):
        pass
        print("sono una cartella")
    else:
        print("sono un file")

        #is_dir = os.path.exists(r"C:\Users\LUIS\Desktop\prova" + f_new)
        #print(is_dir)
        
        try:
            os.mkdir(f_new)
            print("cartella creata")
        except FileExistsError:
            pass
            print("File inseriti nelle rispettive cartelle")
        except FileNotFoundError:
            print("Tutti i file sono stati ordinati")
            
    
        f2 = f_name+f_ext
        shutil.move(f2, f_new)
        

This is the error I get:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/shutil.py", line 803, in move
    os.rename(src, real_dst)
FileNotFoundError: [Errno 2] No such file or directory: '.DS_Store' -> ''

Any help? Thanks

Aniket Tiratkar
  • 798
  • 6
  • 16

1 Answers1

0

The problem is related to hidden OSX files, they follow the .name pattern, in these cases their variable "f_ext" is empty, and consequently f_new too. And that throws an error when you try to move the file "shutil.move (f2, f_new)"

I did I created a small conditional to test this hypothesis and it worked perfectly on my Macbook

import os
import shutil

percorso = input("Inserisci il percorso ")
os.chdir(percorso)

for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    print(os.path.splitext(f))

    if f_ext: # <---------- HERE
        f_new = f_ext[1:len(f_ext)]
    else:
        f_new = 'no_extension'

    if os.path.isdir(f):
        pass
        print("sono una cartella")
    else:
        print("sono un file")

        try:
            os.mkdir(f_new)
            print("cartella creata")
        except FileExistsError:
            pass
            print("File inseriti nelle rispettive cartelle")
        except FileNotFoundError:
            print("Tutti i file sono stati ordinati")

        f2 = f_name + f_ext
        shutil.move(f2, f_new)

Other checks, as if the folder already exists, and only create a new folder if there are no homonyms also need to be implemented. But that code works.