代码之家  ›  专栏  ›  技术社区  ›  lucians

仅更改文件名的一部分

  •  -2
  • lucians  · 技术社区  · 8 年前

    • 区域11.tif
    • 区域12.tif
    • 区域14.tif
    • 区域22.tif
    • 区域25.tif

    我怎样才能只更改最后一个数字,使它们变得有序和“更增量”? 相反,如果 area14.tif 应该是这样的 area13.tif 22/25区也是如此。

    我有一个代码,但它有点坏,因为它删除了一些文件(这很奇怪,我知道…)。

    编辑:已添加(可能已损坏)密码

    try:
        path = (os.path.expanduser('~\\FOLDER\\'))
        files = os.listdir(path)
    
        idx = 0
        for file in files:
            idx =+ 1
            i = 'ex_area'
            if file.endswith('.tif'):
                i = i + str(idx)
                os.rename(os.path.join(path, file), os.path.join(path, str(i) + '.tif'))
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
    
    4 回复  |  直到 8 年前
        1
  •  2
  •   Vlad Lyga    8 年前

    1) 将目录中的文件名读入数组(字符串)。

    3) 对于每个文件名,将字符串切片并插入索引
    4) 重命名

    例如:

    import os
    import glob
    
    [os.rename(n, "{}{}.tif".format(n[:5], i)) for i, n in  enumerate(glob.glob("area*"))]
    
        2
  •  1
  •   user8715867    8 年前

    首先,您可以通过glob模块获得图像路径列表:

    images = glob.glob("/sample/*.tif")
    

    然后,您只需使用操作系统模块重命名它们:

    for i in range(len(images)): os.rename(images[i], ‘area’+i+’.tif’) 
    
        3
  •  1
  •   john    8 年前

    首先将所有文件名重命名为临时名称,然后添加您喜欢的任何名称

    import glob,os
    images = glob.glob("*.tif")
    for i in range(len(images)):
            os.rename(images[i], 'temp_'+str(i)+'.tif')
    
    tempImages = glob.glob("temp*.tif")
    
    for i in range(len(tempImages)):
            os.rename(tempImages[i], 'area'+str(i+1)+'.tif')
    
        4
  •  1
  •   lucians    8 年前

    还找到了另一个解决方案。但这其中有一个小小的不同,最后还有一个更好的方法(至少对我来说):为每个区域创建一个文件夹。很简单,我以前没想过。。。

    顺便说一句,这是代码,评论道。我使用这个只是因为我实现了我想要的。感谢所有的回答,让我学到了新的东西。

    path = (os.path.expanduser('~\\FOLDER\\AREA1\\')) #select folder
    files = os.listdir(path)
    
    i = 1 #counter
    name = 'area' #variable which the file will take as name
    
    for file in files:
        if file.endswith('.tif'): #search only for .tif. Can change with any supported format
            os.rename(os.path.join(path, file), os.path.join(path, name + str(i)+'.tif')) #name + str(i)+'.tif' will take the name and concatenate to first number in counter. #If you put as name "area1" the str(i) will add another number near the name so, here is the second digit.
            i += 1 #do this for every .tif file in the folder
    

    这有点简单,但因为我把文件放在两个单独的文件夹中。如果将文件保存在同一文件夹中,则无法正常工作。

    编辑:现在我看到了,它和我上面的代码一样。。。。