【问题标题】:How to rename multiple file names in python如何在python中重命名多个文件名
【发布时间】:2019-05-04 23:56:15
【问题描述】:

我想重命名文件夹中的多个文件

当前文件名如下:

3321_AD_axial_001_MRI.jpg

3421_AD_axial_098_MRI.jpg

3521_AD_axial_032_MRI.jpg

预期的文件名如下:

images0001.jpg, 图片0002.jpg, images0003.jpg

filepath = "/Users/XYZ/Desktop/SVM-Image-Classification-master/test"

import os 
def main(): 
    i = 0
    for filename in os.listdir("test"): 
        dst ="images" + str(i) + ".jpg"
        src ='test'+ filename 
        dst ='test'+ dst 
        i += 1
        os.rename(scr,dst)
main()

ileNotFoundError                         Traceback (most recent call last)
<ipython-input-47-840511576fe7> in <module>()
     18 
     19     # Calling main() function
---> 20     main()

<ipython-input-47-840511576fe7> in main()
     11         # rename() function will
     12         # rename all the files
---> 13         os.rename(src, dst)
     14         i += 1
     15 

FileNotFoundError: [Errno 2] No such file or directory: 'test0543_AD_axial_099_PET.jpg' -> 'testimage0.jpg'

函数产生错误并且所有文件名保持不变。他们并没有像我预期的那样改变。谢谢!

【问题讨论】:

  • 将 'test' 更改为 'test/'。另外,您的os.rename 中有错字。应该是os.rename(src, dst)

标签: python glob


【解决方案1】:

这里:

import os 
def main(): 
    i = 0
    for filename in os.listdir("test"): 
        dst ="images_" + str(i) + "_.jpg"
        src = filename 
        path = "test/"+src
        newpath = "test/"+dst
        os.rename(path,newpath)
        i += 1
main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-02
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    相关资源
    最近更新 更多