Answer the question
In order to leave comments, you need to log in
How to copy files with the same name under different names, and not overwrite the created file when a file of the same name is found?
PYTHON
Help. The disk has an unknown number of files with the same name "pic one". You need to find them all and make copies, but with different sequential names (example: pic1, pik2, pic3.......) to avoid overwriting the same file found with the same name.
#КОД ИЩЕТ ФАЙЛ И КОПИРУЕТ ЕГО В УКАЗАННОЕ МЕСТО
import os
name = 'pic one.jpg'
disk = ('C:\\')
for root, dirs, files in os.walk(disk):
if name in dirs or name in files:
print(f'We find {name} in {root}')
filen1 = (f'{root}' + str('\\') + f'{name}')
filen2 = 'C:\\Users\\........\\Desktop\\test\\pic.jpg'
file1 = open(filen1, 'rb')
file2 = open(filen2, 'wb')
file2.write(file1.read())
file1.close()
file2.close()
print('COPY COMPLETED')
print ('THE END')
input()
Answer the question
In order to leave comments, you need to log in
There are a few simple rules:
0. Watch for indentation and format the code correctly.
For python, this is the most important rule. You incorrectly set the tags for wrapping the code, I removed the extra ones for you, but your indents in the code are broken. This must be treated carefully.
Remember that in addition to spaces, there are tabs. A tabulation is one wide character, but its width is not regulated anywhere, and python understands its nesting in the code by the number of empty characters at the beginning of the line. By itself, mixing tabs and spaces in Python code leads to terrible confusion and guaranteed errors. Holivars "spaces versus tabs" is not one hundred man-years old, but there is a general rule fixed in the PEP: use 4 spaces as one indent. Always. With no exceptions.
one. Do not use parentheses where they are not needed:
disk = ('C:\\')
filen1 = (f'{root}' + str('\\') + f'{name}')
f'{root}' + str('\\') + f'{name}'
file1 = open(filen1, 'rb')
file2 = open(filen2, 'wb')
file2.write(file1.read())
file1.close()
file2.close()
with open(filen1, 'rb') as file1, open(filen2, 'wb') as file2:
file2.write(file1.read())
directory = Path('path/to/my/dir')
fn1 = directory / 'file1.jpg'
fn2 = directory / 'file2.jpg'
file2.write_bytes(file1.read_bytes())
if name in dirs or name in files:
files = Path('c:').rglob('*.jpg')
Path('file_name_{last_index+1:05}.jpg')
. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question