N
N
Nikita Khan2021-11-17 16:06:02
Python
Nikita Khan, 2021-11-17 16:06:02

How to make sure that when moving files they are not replaced?

Recently on YouTube I caught a glimpse of the idea of ​​how people were making a sorter in a folder.
I tried to do it myself (I'm just learning python), as a result, 2 problems arose.
I needed to move a file from the D:\Downloads directory to the D:\Downloads\Text directory (for example)
I tried to use the function from os replace

if os.path.splitext(file)[1] == '.txt':
                os.replace(file, "D:\Downloads\Text")

Resulting in an error:
Traceback (most recent call last):
File "D:/Python_projects/sorting_downloads/main.py", line 18, in
os.replace(file, "D:\Downloads\Text")
PermissionError: [ WinError 5] Permission denied: 'New text document.txt' -> 'D:\\Downloads\\Text'

Then I decided to connect shutil, and use its function shutil.move
Where I specified the path to the file in the Downloads directory as the first argument , and in the second Text.
Everything worked out, the file was transferred, but if there are files with the same name in Downloads as in Text, then it simply replaces the old file, but I need something like (1)

import os

# import calendar

os.chdir(r"D:\Downloads")
dirs = ['Изображения', 'Видео', 'Торрент', 'Установщики', 'Zip', 'Аудио(Музыка)', 'Остальное', 'Text']
for name in dirs:
    if os.path.isdir(name):
        continue
    os.mkdir(r"{}".format(name))

swaps = True
while True:
    swaps = False
    for file in os.listdir():
        if os.path.isfile(file):
            if os.path.splitext(file)[1] == '.txt':
                os.replace(file, "D:\Downloads\Text")

ps Write how to correctly move a file to another folder using os
pss do not blame me for stupidity

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question