Having Problems with Arguments

2020-02-15 03:26发布

I have tried to write this little script that will batch rename file extensions. I am passing three arguments, the directory where the files are located, the current extension, and the new extension.

The error I am getting is

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

The code is

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)

标签: python
3条回答
贪生不怕死
2楼-- · 2020-02-15 03:49

os.listdir returns only the filenames, not complete paths. Use os.path.join to recreate the correct path:

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))
查看更多
做个烂人
3楼-- · 2020-02-15 04:02

Problem is that os.listdir returns only filenames without path, you should use function os.path.join to join work_dir and filename.

And line newfile = filename.replace(old_ext, new_ext) looks very unsafe because it can replace not only extension but some unexpected parts of filename.

You can replace file extension in more safe way using os.path functions, splitext for example.

查看更多
▲ chillily
4楼-- · 2020-02-15 04:05

You must specify fullname when you are not in the directory (you are not):

os.rename(os.path.join(work_dir, filename), os.path.join(work_dir, newfile))
查看更多
登录 后发表回答