-2

I have a folder with a lot of tutorial links, so I wanted to create a script that reads the file name and for instance, if the file has in its name the word "VBA" or "Excel" it would create the folder Excel and send to it. The same would happen with files containing the word "python".

The code is running, but nothing happens and the files still in the same directory. Does anyone have an idea of what I'm doing wrong?

Here is what I have in the folder, all files are links to youtube tutorials or websites:

enter image description here

Please see my code below:

import os
import shutil

os.chdir(r"C:\Users\RMBORGE\Desktop\Useful stuff")
path = r"C:\Users\RMBORGE\Desktop\Useful stuff\Excel"

for f in os.listdir():
    if "vba" in f:
       shutil.move(os.chdir,path) 
  • The first argument to shutil.move is supposed to be the path of the file you want to move. Why are you passing the function `os.chdir`?? – wwii Aug 31 '22 at 23:14

2 Answers2

1

Try this

import os
import shutil

path_to_files = 'some path'

files = os.listdir(path_to_files)
for f in files:
    if 'Excel' in f:
        created_folder = os.path.join(path_to_files, 'Excel')
        filepath = os.path.join(path_to_files, f)
        os.makedirs(created_folder, exist_ok=True)
        shutil.move(filepath, created_folder)

NB: You can add more if statements for different keywords like Excel

Daniel Afriyie
  • 217
  • 4
  • 12
0

Use pathlib mkdir for creating the folders. Prepare the folders/keywords you want sort in the list 'folders'. And then what is important is skipping the folders because os.listdir() gives you the folders aswell (and there is an error if you want to move a folder into itself)

import os
import shutil
import pathlib

folders = ["vba", "Excel"]

path = "/home/vojta/Desktop/THESIS/"

for f in os.listdir():
    if not os.path.isdir(os.path.join(path, f)): # skip folders
        for fol in folders:
            if fol in f:
                pathlib.Path(os.path.join(path, fol)).mkdir(parents=True, exist_ok=True)
                fol_path = os.path.join(path, fol)
                shutil.move(os.path.join(path, f), os.path.join(fol_path, f)) 
brownie
  • 121
  • 9