2012-08-06 42 views
1

我試圖寫這個小批量重命名文件擴展名的腳本。我傳遞了三個參數,即文件所在的目錄,當前擴展和新​​擴展。與參數有問題

我得到的錯誤是

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

[IOError當試圖打開現有文件]可能的重複(http://stackoverflow.com/questions/10802418/ioerror-when-trying-to-open-existing-files) – 2012-08-06 09:55:08

+0

也見[python os.rename (...)將無法使用!](http://stackoverflow.com/q/4147438) – 2012-08-06 10:26:48

回答

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

你忘記了第二個os.path.join – 2012-08-06 09:53:24

+0

@IgorChubin:謝謝,糾正。 – 2012-08-06 09:54:43

+0

非常感謝已排序的問題 – geekcomputers 2012-08-06 10:04:22

0

您必須指定全名時,你是不是在目錄(你是不是):

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

問題是,os.listdir只返回文件名不帶路徑,你應使用功能os.path.join加入work_dirfilename

而行newfile = filename.replace(old_ext, new_ext)看起來非常不安全,因爲它不僅可以替換擴展名,還可以替換文件名的一些意想不到的部分。

例如,您可以使用os.path函數以更安全的方式替換文件擴展名,例如splitext