[英]How do I copy files in a folder directory with a specific extension and save it to a new folder with out overwriting copied files?
Here is the code I am working on: 这是我正在处理的代码:
from qgis.core import*
import glob, os, shutil, time, qgis
path = r"C:\Temp\testinput"
dest = r"C:\Temp\testoutput"
fname = []
for root,d_names,f_names in os.walk(path):
for f in f_names:
if f.endswith('.kml'):
src = os.path.join(root,f)
print(time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(src))))
print(os.path.realpath(src))
shutil.copy2(src, dest)
this code transverses through the directory and copies the files but does overwrites files with the same name. 此代码遍历目录并复制文件,但确实覆盖了具有相同名称的文件。 How do I prevent the overwriting part?
如何防止覆盖部分? I would like to have the same type of filed renamed to "filename-copy" if it catches a file with the same name in the new folder.
我想将相同类型的文件名重命名为“ filename-copy”,如果它在新文件夹中捕获了一个具有相同名称的文件。
Very quick answer; 很快的答案;
If the extension is known, it is not that hard. 如果知道扩展名,那就不难了。 You can check upfront if a file exists.
您可以预先检查文件是否存在。 By adding something like this
通过添加这样的东西
exists = os.path.isfile(dest)
if exists:
os.rename(dest , dest.replace('.kml', '-copy.kml'))
So the entire thing looks like this: 所以整个事情看起来像这样:
from qgis.core import*
import glob, os, shutil, time, qgis
path = r"C:\Temp\testinput"
dest = r"C:\Temp\testoutput"
fname = []
for root,d_names,f_names in os.walk(path):
for f in f_names:
if f.endswith('.kml'):
src = os.path.join(root,f)
print(time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(src))))
print(os.path.realpath(src))
exists = os.path.isfile(dest)
if exists:
os.rename(dest , dest.replace('.kml', '-copy.kml'))
shutil.copy2(src, dest)
Not so very quick answer; 回答不是那么迅速。
But, this assumes that the "file-copy.kml" does not already exist. 但是,这假定“ file-copy.kml”尚不存在。 If you want to keep an X amount of copies, perhaps rename them differently.
如果要保留X份副本,则可以使用其他名称重命名。 In that case, I would advice something like this:
在这种情况下,我建议如下:
exists = os.path.isfile(dest)
if exists:
os.rename(dest , dest.replace('.kml', '-copy_'+id_generator()+'.kml'))
Where you place this someplace at the top of your file. 将此位置放置在文件顶部的位置。
import string
import random
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
Where I have borrowed the function that generates some random characters from this question; 我在哪里借用了从该问题生成一些随机字符的函数; Random string generation with upper case letters and digits in Python
在Python中使用大写字母和数字生成随机字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.