Исключение SameFileError в shutil.move - PullRequest
0 голосов
/ 17 февраля 2020

Я написал скрипт для сортировки файлов из папки в определенные c подпапки на основе данных в листе Excel.

Подпапки могут содержать файлы, которые были ранее отсортированы. Я ожидаю, что скрипт переместит и заменит любые дубликаты файлов.

Сценарий отлично работает при использовании его в одном каталоге, но я попытался использовать его в другом каталоге, и он выдал исключение SameFileError. Насколько я понимаю, использование функции shutil.move заменит файл, а не вызовет исключение SameFileError.

Первый (успешный) каталог находился в папках Dropbox. Второй (неудачный) был в папках GDrive. path1 отразил изменения в пути. Может ли использование этого сценария в облачных каталогах привести к исключению SameFileError? Если нет, то любая помощь относительно того, почему это происходит, приветствуется.

Скрипт: Transfer2.py

from xlrd import open_workbook 
import shutil
import os 

path1 = 'name of path'
folder = '\To be sorted\Export'
basepath = path1 + folder
#get export
export = xlrd.open_workbook(basepath + '\export.xlsx')
#number of rows and cols
sheet = export.sheet_by_index(0)
NumRows = sheet.nrows
NumColumns = sheet.ncols
count = 0
file_list=[] #for number of images

#path to images
ubasepath= path1 + '\To be sorted'

for images in os.listdir(ubasepath):
    if os.path.isfile(os.path.join(ubasepath, images)):
        file_list.append(images)
NumImages = len(file_list)

for j in range(0,NumRows):#loop over export rows
    for p in range(1, NumColumns): #loop through export columns
        for k in range (0, NumImages):
            String = 'someconstantstring' + file_list[k] #image file name in export
            imagename = sheet.cell_value(j,p)
            visit = sheet.cell_value(j,2)
            if imagename == String:
                print(file_list[k])
                subject = sheet.cell_value(j,0)
                print(subject)
                if visit == 'Unscheduled Visit':
                    for col in range(0, NumColumns):#determine column of Visit Date 
                        datecol = sheet.cell_value(0, col)
                        if datecol == 'Visit Date_VISDATE':                
                            visdate = sheet.cell_value(j,col)
                            visit = visit + " " + visdate
                d1 = ubasepath + '\\' + file_list[k] #image file path
                d2 = path1 + '\\' + subject + '\\' + visit + '\\' + file_list[k] #subject folder
                os.makedirs(os.path.dirname(d2), exist_ok=True) #if the path doesn't exist, create folder
                shutil.move(d1, d2)
                count = count + 1
                print(count)
            else: 
                count = count + 1
                print(count)

В результате:

Traceback (most recent call last):

  File "C:\Users\brean\Anaconda3\lib\shutil.py", line 566, in move
    os.rename(src, real_dst)

FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'G:\\path1\\folder\\filename' -> 'G:\\path1\\folder\\filename'


During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "<ipython-input-1-761efa6a40a1>", line 1, in <module>
    runfile('G:/path1/transfer2.py', wdir='G:/path1')

  File "C:\Users\brean\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\brean\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "G:/path1/transfer2.py", line 45, in <module>
    shutil.move(d1, d2)

  File "C:\Users\brean\Anaconda3\lib\shutil.py", line 580, in move
    copy_function(src, real_dst)

  File "C:\Users\brean\Anaconda3\lib\shutil.py", line 266, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)

  File "C:\Users\brean\Anaconda3\lib\shutil.py", line 104, in copyfile
    raise SameFileError("{!r} and {!r} are the same file".format(src, dst))

SameFileError: 'G:\\path1\\To be sorted\\filename' and 'G:\\path1\\folder\\filename' are the same file
...