Reputation: 1
i'm trying to move .lnk files from the desktop to a folder.
I tried with os and shutil but they don't work.
my code is more complex, it sends all the file in a folder order by their extension, but with .lnk, it doesn't work
import os
import shutil
desktop = os.listdir("C:\\Users\\Utente\\Desktop")
desktop.sort()
categories = {
'.txt': 'documenti di testo', '.xlsx': 'fogli di calcolo',
'.png': 'immagini', '.jpg': 'immagini', '.jpeg': 'immagini',
'.zip': 'file zip', '.exe': 'programmi', '.pkt': 'PacketTracer',
'.pdf': 'documenti vari', '.docx': 'WORD', '.pptx': 'PowerPoint',
'.lnk': 'Collegamenti', '.py': 'codici vari', '.cpp': 'codici',
'.html': 'codici vari', '.php': 'codici vari', '.js': 'codici vari',
}
url = "C:\\Users\\Utente\\Desktop\\"
def move_file(file_name, folder_name):
try:
shutil.move(url + file_name, url + folder_name + "\\" + file_name)
except Exception as e:
print(e)
def organize_files():
for file_name in desktop:
if file_name == "ordina_desktop.py":
continue # Ignora il file "ordina_desktop.py" sul desktop
if os.path.isfile(url + file_name):
file_extension = os.path.splitext(file_name)[1].lower()
if file_extension in categories:
folder_name = categories[file_extension]
if not os.path.exists(url + folder_name):
try:
os.makedirs(url + folder_name)
except Exception as e:
print(e)
move_file(file_name, folder_name)
else:
folder_name = "altro"
if not os.path.exists(url + folder_name):
try:
os.makedirs(url + folder_name)
except Exception as e:
print(e)
move_file(file_name, folder_name)
elif os.path.isdir(url + file_name) and file_name not in categories.values():
if file_name != "altro":
folder_name = "altro"
if not os.path.exists(url + folder_name):
try:
os.makedirs(url + folder_name)
except Exception as e:
print(e)
move_file(file_name, folder_name)
organize_files()
how can i do it?
Upvotes: 0
Views: 44
Reputation: 11857
For a simple task like move all files to sub folders of same extension, it's easier to use the windows shell to do the heavier tasks that it was designed for.
So to move all those files to a subfolder based on extension, we can in the target folder simply run a cmd file at the target location for example the users desktop
MoveToSubs.cmd
cd /d "%USERPROFILE%\Desktop"
setlocal ENABLEDELAYEDEXPANSION
for %%f in (dir /b *.*) do (
set "g=%%~xf"
if not exist !g:~1! md !g:~1!
move "%%f" !g:~1!
)
A slight quirk with this method is that there can be an empty folder ~1 in addition but it's easy to delete by add one more cmd line if it's empty.
So from Python simply run the cmd via OS, For a more versatile use add an argument so
MoveToSubs.cmd "%USERPROFILE%\Desktop"
And replace the first cmd line with
cd /d "%~dp1"
Upvotes: 0