【问题标题】:Can't resolve WindowsError: [Error 2] The system cannot find the file specifiedCan't resolve WindowsError: [Error 2] The system cannot find the file specified
【发布时间】:2011-12-30 15:42:07
【问题描述】:

我正在尝试重命名目录中的所有图片。我需要在文件名中添加几个前置零。我是 Python 新手,我编写了以下脚本。

import os

path = "c:\\tmp"
dirList = os.listdir(path)

for fname in dirList:
    fileName = os.path.splitext(fname)[0]
    fileName = "00" + fname
    os.rename(fname, fileName)
    #print(fileName)

注释打印行只是为了验证我是否走在正确的轨道上。当我运行它时,我收到以下错误,我不知道如何解决它。

Traceback(最近一次调用最后一次):文件 “C:\Python32\Code\add_zeros_to_std_imgs.py”,第 15 行,在 os.rename(fname, fileName) WindowsError: [错误2] 系统找不到指定的文件

非常感谢任何帮助。谢谢。

【问题讨论】:

    标签: python


    【解决方案1】:

    您应该将绝对路径传递给os.rename。现在你只传递文件名本身。它没有找到正确的位置。使用os.path.join

    试试这个:

    import os
    
    path = "c:\\tmp"
    dirList = os.listdir(path)
    
    for fname in dirList:
        fileName = os.path.splitext(fname)[0]
        fileName = "00" + fname
        os.rename(os.path.join(path, fname), os.path.join(path, fileName))
        #print(fileName)
    

    【讨论】:

      猜你喜欢
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2020-01-24
      • 2011-09-18
      • 2022-12-22
      • 1970-01-01
      • 2020-04-22
      相关资源
      最近更新 更多