Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - making copies of a file

Tags:

python

file

copy

I have a file that I want copied into a directory multiple times. It could be 100, it could be 1000. That's a variable.

I came up with this:

import shutil

count = 0
while (count < 100):
    shutil.copy2('/Users/bubble/Desktop/script.py', '/Users/bubble/Desktop/pics')
    count = count + 1

It puts 1 copy of the file in the directory, but only 1 file. My guess is that it doesn't automatically add a 2,3,4,5 etc onto the end of the file as it would if you were copying and pasting.

Any ideas how to do this?

Regards.

like image 203
BubbleMonster Avatar asked Jul 27 '13 10:07

BubbleMonster


People also ask

Can Python copy files?

copyfile() method in Python is used to copy the content of the source file to the destination file. The metadata of the file is not copied. Source and destination must represent a file and destination must be writable.


1 Answers

Use str.format:

import shutil

for i in range(100):
    shutil.copy2('/Users/bubble/Desktop/script.py', '/Users/bubble/Desktop/pics/script{}.py'.format(i))

To make it even more useful, one can add the format specifier {:03d} (3 digit numbers, i.e. 001, 002 etc.) or {:04d} (4 digit numbers, i.e. 0001, 0002 etc.) according to their needs as suggested by @Roland Smith.

like image 171
falsetru Avatar answered Sep 28 '22 19:09

falsetru