遇到参数问题

时间:2012-08-06 09:48:39

标签: python

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

我得到的错误是

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)

3 个答案:

答案 0 :(得分:6)

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))

答案 1 :(得分:0)

当您不在目录中时,您必须指定fullname(您不是):

os.rename(os.path.join(work_dir, filename), os.path.join(work_dir, newfile))

答案 2 :(得分:0)

问题是os.listdir仅返回没有路径的文件名,您应该使用函数os.path.join加入work_dirfilename

newfile = filename.replace(old_ext, new_ext)看起来非常不安全,因为它不仅可以替换扩展名,还可以替换文件名的一些意外部分。

您可以使用os.path函数splitext以更安全的方式替换文件扩展名。

相关问题