Python 文件重命名

标签 python

我的目录中有一些文件,

file_IL.txt
file_IL.csv
file_NY.txt
file_NY.csv

我必须重命名它们,以便它们获得序列号。例如,

file_IL.txt_001
file_IL.csv_001
file_NY.txt_002
文件_NY.csv_002

我编写了以下Python代码

def __init__(self):  

    self.indir = "C:\Files"  



def __call__(self):  

    found = glob.glob(self.indir + '/file*')  

    length = len(glob.glob(self.indir + '/file*'))  
    print length  
    count = 000  

    for num in (glob.glob(self.indir + '/file*')):  
        count = count + 1  
        count = str(count)  
        print count  
        shutil.copy(num, num+'_'+count)  
        print num  
        count = int(count)  

但这给了我如下结果,

file_IL.txt_001
file_IL.csv_002
file_NY.txt_003
文件_NY.csv_004

有人可以帮我修改上面的Python脚本来满足我的要求吗?我是 Python 新手,不知道如何实现它。

最佳答案

最好的方法是将扩展名存储在字典中并对该扩展名进行计数。

def __call__(self):  

    found = glob.glob(self.indir + '/file*')  
    length = len(found)  
    counts = {}

    for num in found:
        ext = num.rsplit(".",1)[-1]    # Right split to get the extension
        count = counts.get(ext,0) + 1  # get the count, or the default of 0 and add 1
        shutil.copy(num, num+'_'+'%03d' % count)   # Fill to 3 zeros
        counts[ext] = count            # Store the new count

关于Python 文件重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19624568/

相关文章:

python - 在 pandas 中合并表时添加默认值

python - 如何在Python/Linux中更快地加载和重新采样(MP3)音频文件?

python - 扩展 django 管理模板

python - 在 python 中使用 cv2 读取 pgm 图像

python - 如何在 3D Matplotlib 散点图中为特定的网格线/刻度线着色?

python 导入循环依赖(也许还有函数声明)

python - 匹配 2 个数据集之间列中的值,更新多个列

python - 如何根据两个不同的 pandas 数据框中的两列查找相同行的索引?

python - 在python类中创建pybullet客户端的多个实例

python - 如何用Python检查一个单词是否是英文单词?