2017-08-25 67 views
0

我正在寫下面的代碼來刪除數字和特殊字符,如果它們出現在文件名的開頭。我有一個工作版本的代碼,但我正在嘗試幾件事情,我注意到一些讓我困惑的東西。FileNotFoundError - 如果我沒有os.chdir到目錄

下面是可以正常工作的代碼。

import re 
import os 

DIR = 'C:\Rohit\Study\Python\Python_Programs\Basics\OOP' 
os.chdir(DIR) 

for file in os.listdir(DIR): 
    if os.path.isfile(os.path.join(DIR, file)): 
     fname, ext = os.path.splitext(file) 
     fname = re.sub(r'(^[0-9. _-]*)(?=[A-Za-z])', "", fname) 
     new_name = fname + ext 
     os.rename(file, new_name) 

但是,如果我只是從上面的代碼中刪除行os.chdir(DIR),我開始得到下面的錯誤。

FileNotFoundError: [WinError 2] The system cannot find the file specified: '6738903-. --__..76 test.py' 

下面是引發錯誤的代碼。

DIR_PATH = r'C:\Rohit\Study\Python\Python_Programs\Basics\OOP' 

for file in os.listdir(DIR): 
    if os.path.isfile(os.path.join(DIR, file)): 
     fname, ext = os.path.splitext(file) 
     fname = re.sub(r'(^[0-9. _-]*)(?=[A-Za-z])', "", fname) 
     new_name = fname + ext 
     os.rename(file, new_name) 

錯誤正在生成os.rename()行。 所以任何人都可以請建議我在這裏做錯了什麼?

回答

2

如果file不是相對於當前目錄的有效路徑(如果沒有執行chdir則不是這種情況),應該爲rename提供完整路徑。否則,你如何期待函數找到要重命名的文件?你在isfile中用os.path.join做得很好,爲什麼不用重命名呢?

DIR_PATH = r'C:\Rohit\Study\Python\Python_Programs\Basics\OOP' 

for file in os.listdir(DIR): 
    full_path = os.path.join(DIR, file) 
    if os.path.isfile(full_path): 
     fname, ext = os.path.splitext(file) 
     fname = re.sub(r'(^[0-9. _-]*)(?=[A-Za-z])', "", fname) 
     new_name = fname + ext 
     os.rename(full_path, os.path.join(DIR, new_name)) 
+0

非常感謝,我不好,我根本沒看它,顯然os.rename(file,new_name)會在當前路徑中找到該文件。對不起這是我的錯。 – Rohit

+0

@Rohit也不是Anis爲路徑使用原始前綴,所以他不需要在反斜槓之後大寫所有字母來解決「奇怪問題」:) –

+2

也注意到chdir是不好的做法:如果另一個模塊期望另一個當前目錄?這將是一場戰鬥。不惜一切代價避免。 –

相關問題