将文件复制到新位置并增加文件名python [英] Copy a file to a new location and increment filename, python

查看:96
本文介绍了将文件复制到新位置并增加文件名python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试:

  1. 浏览一堆文件
  2. 进行一些更改
  3. 将旧文件复制到子目录.这是我不想覆盖新目录中的文件的踢脚板(如果该文件已经存在). (例如,如果"Filename.mxd"已经存在,则复制并重命名为"Filename_1.mxd".如果存在"Filename_1.mxd",则将文件复制为"Filename_2.mxd",依此类推...)
  4. 保存文件(但保存而不是另存为,这样它会覆盖现有文件)

它是这样的:

for filename in glob.glob(os.path.join(folderPath, "*.mxd")):
    fullpath = os.path.join(folderPath, filename)

    mxd = arcpy.mapping.MapDocument(filename)

    if os.path.isfile(fullpath):
        basename, filename2 = os.path.split(fullpath)


    # Make some changes to my file here

    # Copy the in memory file to a new location. If the file name already exists, then rename the file with the next instance of i (e.g. filename + "_" + i)

    for i in range(50):
        if i > 0:
            print "Test1"
            if arcpy.Exists(draftloc + "\\" + filename2) or arcpy.Exists(draftloc + "\\" + shortname + "_" + str(i) + extension):
                print "Test2"
                pass
            else:
                print "Test3"
                arcpy.Copy_management(filename2, draftloc + "\\" + shortname + "_" + str(i) + extension)
    mxd.save()

因此,我决定要做的2件事是将文件范围设置为远远超出我期望的范围(50).我敢肯定,有一种更好的方法,只需增加到下一个数字而不设置范围即可.

So, 2 things I decided to do, was to just set the range of files well beyond what I expect to ever occur (50). I'm sure there's a better way of doing this, by just incrementing to the next number without setting a range.

您可能会看到的第二件事是,脚本将所有内容保存在该范围内.我只想在下一个不会发生的i实例上保存一次.

The second thing, as you may see, is that the script saves everything in the range. I just want to save it once on the next instance of i that does not occur.

希望这很有意义,

迈克

推荐答案

由于上面的Maty建议,我想出了答案.对于那些感兴趣的人,我的代码是:

thanks to Maty suggestion above, I've come up with my answer. For those who are interested, my code is:

    result_name = filename2
    print result_name
    i = 0

    # Check if file exists
    if arcpy.Exists(draftloc + "\\" + result_name):
        # If it does, increment i by 1
        i+=1
        # While each successive filename (including i) does not exists, then save the next filename
        while not arcpy.Exists(draftloc + "\\" + shortname + "_" + str(i) + extension):                
            mxd.saveACopy(draftloc + "\\" + shortname + "_" + str(i) + extension)            
    # else if the original file didn't satisfy the if, the save it.
    else:           
        mxd.saveACopy(draftloc + "\\" + result_name)

这篇关于将文件复制到新位置并增加文件名python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆