FileNotFoundError - 如果我没有os.chdir到DIRECTORY

时间:2017-08-25 10:34:26

标签: python

我正在编写以下代码,如果它们出现在文件名的开头,则删除数字和特殊字符。我有一个工作版本的代码,但我正在尝试一些事情,我注意到一些让我困惑的事情。

以下是可以正常使用的代码。

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()行上生成的。 所以任何人都可以建议我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

如果file不是相对于当前目录的有效路径(如果您不执行chdir则不是这种情况),则应提供rename完整路径。否则,您如何期望该函数找到要重命名的文件?您在os.path.join中使用isfile为什么不重命名?

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