Python 文件重命名程序 - 绝对路径问题
Python file rename program - abspath issue
在下面的代码中,我无法将重命名的文件保存在与原始文件相同的目录中 /Users/xxx/Documents/Dates
我正在寻求帮助来解释原因?
#! usr/bin/env python3
# renameDates.py - Renames filenames with America MM-DD-YYYY date format
# to European DD-MM-YYYY
import shutil, os, re
#create a regex that matches files with the America date format.
datePattern = re.compile(r'''^(.*?) # all text before the date
((0|1)?\d)- #one or two digits for the month
((0|1|2|3)?\d)- #one or two digits for the day
((19|20)\d\d) #four digits for the year
(.*?)$ #all text after the date
''', re.VERBOSE)
for amerFilename in os.listdir('/Users/xxx/Documents/Dates'):
mo = datePattern.search(amerFilename)
if mo == None:
continue
beforePart = mo.group(1)
monthPart = mo.group(2)
dayPart = mo.group(4)
yearPart = mo.group(6)
afterPart = mo.group(8)
euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart
absWorkingDir = os.path.abspath('./Dates')
amerFilename = os.path.join(absWorkingDir, amerFilename)
print('Renaming "%s" to :%s:...' % (amerFilename, euroFilename))
shutil.move(amerFilename, euroFilename) #uncomment after testing
您在 for
语句中从特定目录 ('/Users/xxx/Documents/Dates') 中提取 amerFilename 文件。但是随后您将它们移动到定义为文件名的 euroFilename,但未在同一特定目录中定义。
如果您将最后一行更改为:
shutil.move(amerFilename, os.path.join('/Users/xxx/Documents/Dates', euroFilename))
...你得到你想要的了吗?
在下面的代码中,我无法将重命名的文件保存在与原始文件相同的目录中 /Users/xxx/Documents/Dates
我正在寻求帮助来解释原因?
#! usr/bin/env python3
# renameDates.py - Renames filenames with America MM-DD-YYYY date format
# to European DD-MM-YYYY
import shutil, os, re
#create a regex that matches files with the America date format.
datePattern = re.compile(r'''^(.*?) # all text before the date
((0|1)?\d)- #one or two digits for the month
((0|1|2|3)?\d)- #one or two digits for the day
((19|20)\d\d) #four digits for the year
(.*?)$ #all text after the date
''', re.VERBOSE)
for amerFilename in os.listdir('/Users/xxx/Documents/Dates'):
mo = datePattern.search(amerFilename)
if mo == None:
continue
beforePart = mo.group(1)
monthPart = mo.group(2)
dayPart = mo.group(4)
yearPart = mo.group(6)
afterPart = mo.group(8)
euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart
absWorkingDir = os.path.abspath('./Dates')
amerFilename = os.path.join(absWorkingDir, amerFilename)
print('Renaming "%s" to :%s:...' % (amerFilename, euroFilename))
shutil.move(amerFilename, euroFilename) #uncomment after testing
您在 for
语句中从特定目录 ('/Users/xxx/Documents/Dates') 中提取 amerFilename 文件。但是随后您将它们移动到定义为文件名的 euroFilename,但未在同一特定目录中定义。
如果您将最后一行更改为:
shutil.move(amerFilename, os.path.join('/Users/xxx/Documents/Dates', euroFilename))
...你得到你想要的了吗?