Change language

Python | Arrange files in directories according to extensions

| |

Below is the Python implementation —

import os  # Using system functions

 

import shutil # Move the file to different folders.

  
# Change the folder location.
os.chdir (os.getcwd ())

cwd = os.getcwd ()

 
# To print files from a folder.

 

l = [f for f in os.listdir (cwd) if os.path.isfile (f)] 

l2 = []

 
# Get file extension from l list.

 

for   value in l:

  s = value.split ( ’.’ ) [ 1

  l2.append (s)

print (l, l2)

  
# Remove duplicate values ​​from
# list l2 and check if the directory is
# exists otherwise we create a new one

  

for extension in set (l2):

  dirname = extension 

if os.path.exists (cwd + ’’ + extension):

  pass

else :

os.makedirs (dirname)

 
# We use the zip function and enumerate l and
# l2 passed as an argument.
# If the extension in the file is the same
# file does not exist, we are moving the file.

 

for files, extension in zip (l, l2):

if extension in file s:

if os.path .exists (cwd + ’’ + extension + ’ + files):

pass

else :

  shutil.move (cwd + ’ ’+ files, cwd +’ + extension)

print (extension, files)

else :

  print ( ’ error’ )

Files not located:

Files are located:

Exit:

 [’arrange .py’, ’mydata.pdf’,’ python.exe’, ’resume.doc’] [’ py’, ’pdf’,’ exe’, ’doc’] py arrange.py pdf mydata.pdf exe python. exe doc resume.doc 

Python | Arrange files in directories according to extensions _files: Questions

Python | Arrange files in directories according to extensions File handling: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method