LivingDeath
LivingDeath

Reputation: 13

Trying to move files into subfolders with shutil.move()

I'm trying to make a code that takes all the files in one directory and organizes them into subdirectories. i.e. 2017.2.3, 2016.2.5, 2015.5.6, 2014.3.5 into folders labeled 2017, 2016, 2015, 2014 within the original directory. Using 2.7.13

The code I'm using is below:

import os, shutil

root_path = ('D:\Sigma\Rides')
folders = ['2016', '2017', '2018', '2019', '2020']
for folder in folders:
   os.mkdir(os.path.join(root_path,folder))

source = os.listdir('D:\\Sigma\\Rides')
dest1 = ('D:\\Sigma\\Rides\\2016')
dest2 = ('D:\\Sigma\\Rides\\2017')
dest3 = ('D:\\Sigma\\Rides\\2018')
dest4 = ('D:\\Sigma\\Rides\\2019')
dest5 = ('D:\\Sigma\\Rides\\2020')


for files in source:
    if (files.startswith('2016_')):
        shutil.move(os.path.join(source, files), dest1)
    if (files.startswith('2017')):           
        shutil.move(os.path.join(source, files), dest2)
    if (files.startswith('2018')):
        shutil.move(os.path.join(source, files), dest3)
    if (files.startswith('2019')):
        shutil.move(os.path.join(source, files), dest4)
    if (files.startswith('2020')):
        shutil.move(os.path.join(source, files), dest5)

This is the error I receieve:

Traceback (most recent call last):
  File "D:\Documents\Programs\Sigma_File_Move.py", line 24, in <module>
    shutil.move(os.path.join(source, files), dest1)
  File "D:\Python27\ArcGIS10.4\lib\ntpath.py", line 65, in join
    result_drive, result_path = splitdrive(path)
  File "D:\Python27\ArcGIS10.4\lib\ntpath.py", line 116, in splitdrive
    normp = p.replace(altsep, sep)
AttributeError: 'list' object has no attribute 'replace'

Any feedback would be greatly appreciated.

Upvotes: 1

Views: 1176

Answers (1)

anupsabraham
anupsabraham

Reputation: 3069

The problem here is that you're trying to create the source file path by joining source variable and files. Here source is a list of all the files and folders in your "Rides" directory. It is not possible to join a list of files and folders to a folder name. That is why the error is happening.

So replacing os.path.join(source, files) to os.path.join(root_path, files) should work for you.

if (files.startswith('2016_')):
    shutil.move(os.path.join(source, files), dest1)

should be changed to

if (files.startswith('2016_')):
    shutil.move(os.path.join(root_path, files), dest1)

Upvotes: 2

Related Questions