【发布时间】:2017-08-25 10:34:25
【问题描述】:
我正在编写以下代码来删除出现在文件名开头的数字和特殊字符。我有一个工作版本的代码,但是我尝试了一些东西,但我发现了一些让我感到困惑的东西。
下面是可以正常工作的代码。
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() 行生成。
那么谁能建议我在这里做错了什么?
【问题讨论】:
标签: python