[英]Python. File Operations
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()
How do I copy the file in the destination folder if it already exists? 如果文件已经存在,如何将其复制到目标文件夹中? The newer file should be renamed to something like filename.x.ext. 较新的文件应重命名为filename.x.ext之类的文件。
Eg- If I try to copy newfile.jpg
and it already exists in the folder, it should get copied as newfile.1.jpg
. 例如,如果我尝试复制newfile.jpg
并且它已经存在于文件夹中,则应将其复制为newfile.1.jpg
。 If newfile.1.jpg
also exists already, the new file should be named newfile.2.jpg
and so on 如果newfile.1.jpg
也已经存在,则新文件应命名为newfile.2.jpg
,依此类推
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
I think that would work 我认为那行得通
then just call it as 然后称之为
shutil.copy2(s, getUniqueName(d))
wont help when you do shutil.copytree
当您做shutil.copytree
时不会帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.