争论有问题

发布于 2021-01-29 15:03:29

我试图编写这个小脚本来批量重命名文件扩展名。我传递了三个参数,即文件所在的目录,当前扩展名和新扩展名。

我得到的错误是

python batch_file_rename_2.py c:\craig .txt .html
Traceback (most recent call last):
  File "batch_file_rename_2.py", line 13, in <module>
  os.rename(filename, newfile) 
WindowsError: [Error 2] The system cannot find the file specified

该代码是

import os
import sys

work_dir=sys.argv[1]
old_ext=sys.argv[2]
new_ext=sys.argv[3]

files = os.listdir(work_dir)
for filename in files:
    file_ext = os.path.splitext(filename)[1]
    if old_ext == file_ext:
        newfile = filename.replace(old_ext, new_ext)
        os.rename(filename, newfile)
关注者
0
被浏览
43
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    os.listdir仅返回文件名,不返回完整路径。使用os.path.join重新创建正确的路径:

    for filename in files:
        file_ext = os.path.splitext(filename)[1]
        if old_ext == file_ext:
            newfile = filename.replace(old_ext, new_ext)
            os.rename(
                os.path.join(work_dir, filename), 
                os.path.join(work_dir, newfile))
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看