I made a python download sorter but there's a little error called [WinError 3] The system cannot find the path specified: ''

Question:

The Problem is there’s an error when i run the script called
this

terminal log
here’s the script:

import os

# Get a list of all the files in the current directory
files = os.listdir('.')

# Sort according to extention
files.sort(key=lambda x: x.split('.')[-1])

# for loop to itrate thru list
for file in files:
  # base name and extention split eg. joe .mama (folder: mama; folder chya andar: joe)
  name, extension = os.path.splitext(file)

  #pahale directory banwachi, if dosent exist
  directory = extension[1:]
  if not os.path.exists(directory):
    os.makedirs(directory)
  

  # Move the file into the directory for its file extension
  os.rename(file, f'{directory}/{file}')

any help will be appreciated thanks : ) <3

the script was working fine when i ran it for the fist time but when i ran it for second time there’s this error

Asked By: Utkarsh Kale

||

Answers:

Your code isn’t handling files with no extension, add some handling for that. for example;

import os

# Get a list of all the files in the current directory
files = os.listdir('.')

# Sort according to extention
files.sort(key=lambda x: x.split('.')[-1])

# for loop to itrate thru list
for file in files:
  # base name and extention split eg. joe .mama (folder: mama; folder chya andar: joe)
  name, extension = os.path.splitext(file)

  #pahale directory banwachi, if dosent exist
  directory = extension[1:] if extension[1:] != '' else 'None'
  if not os.path.exists(directory):
    os.makedirs(directory)
  

  # Move the file into the directory for its file extension
  os.rename(file, f'{directory}/{file}')
Answered By: Sean Conkie

here’s a better version of the code I wrote

import os
import shutil

# Sort and move files according to their extension

# Get a list of all the files in the current directory
files = os.listdir('.')

# Sort the files by extension
files.sort(key=lambda x: os.path.splitext(x)[1])

# Iterate through the files
for file in files:
  # Split the file name and extension
  name, extension = os.path.splitext(file)

  # Create the destination directory for the file
  if extension != '':
      directory = extension[1:]
      if not os.path.exists(directory):
          os.makedirs(directory)
  else:
      directory = 'None'

  # Move the file to the destination directory
  shutil.move(file, os.path.join(directory, file))

thanks for the help : )

Answered By: Utkarsh Kale
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.