Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

python - Having Problems with Arguments

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...