-1
def copytree(src, dst, symlinks=False, ignore=None):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            print "copying"
            shutil.copytree(s, d, symlinks, ignore=None)
        else:
            shutil.copy2(s, d)
def main ():
    #path to input
    src="/home/user/abcd"
    #here path to output
    dst="/home/user/dirtest"
    copytree(src,dst)

if __name__ == '__main__':
    main()

ファイルが既に存在する場合、宛先フォルダーにファイルをコピーするにはどうすればよいですか? 新しいファイルは filename.x.ext のような名前に変更する必要があります。

例-コピーしようnewfile.jpgとして、フォルダーに既に存在する場合、としてコピーされるはずですnewfile.1.jpg。既に存在する場合newfile.1.jpgは、新しいファイルに名前newfile.2.jpgを付ける必要があります。

4

1 に答える 1

2
def getUniqueName(destPath):
   d = destPath[:]
   count = 0
   while os.path.exists(d):
      count += 1 
      parts = os.path.splitext(d)
      d = "%s.%s%s"%(parts[0],count,parts[1])
   return d

私はそれがうまくいくと思う

次に、次のように呼び出します

shutil.copy2(s, getUniqueName(d))

あなたがするときに助けませんshutil.copytree

于 2013-03-28T16:02:00.710 に答える