【问题标题】:Copy a file to a new location and increment filename, python将文件复制到新位置并增加文件名,python
【发布时间】:2012-04-19 15:48:22
【问题描述】:

我正在尝试:

  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()

所以,我决定做两件事,就是将文件范围设置为远远超出我预期的范围 (50)。我确信有更好的方法可以做到这一点,只需递增到下一个数字而不设置范围。

如您所见,第二件事是脚本保存了范围内的所有内容。我只想在下一个不发生的 i 实例上保存一次。

希望这是有道理的,

迈克

【问题讨论】:

    标签: python auto-increment


    【解决方案1】:

    使用 while 循环而不是 for 循环。使用while循环找到合适的i,然后保存。

    代码/伪代码如下所示:

    result_name = original name
    i = 0
    while arcpy.Exists(result_name):
        i+=1
        result_name = draftloc + "\\" + shortname + "_" + str(i) + extension
    save as result_name
    

    这应该可以解决这两个问题。

    【讨论】:

      【解决方案2】:

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

          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)
      

      【讨论】:

        猜你喜欢
        • 2018-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-30
        • 1970-01-01
        • 2012-01-01
        • 1970-01-01
        相关资源
        最近更新 更多