I am working through the renameDates project in Automate the Boring stuff. It's supposed to match dates formated the American way and change them to the European format.
我正在通过自动化无聊的东西中的renameDates项目。它应该匹配形成美国方式的日期并将其更改为欧洲格式。
The thing I don't understand about this code is, how does it find the correct directory?
我对这段代码不了解的是,它如何找到正确的目录?
I can't find any code that sets the current working directory to the file I need it to work in, but the script seems written assuming the default current working directory is where it should work.
我找不到任何将当前工作目录设置为我需要它工作的文件的代码,但是脚本似乎是假定默认的当前工作目录应该在哪里工作。
Is it something simple like, running the script from the file I want to search for regular expressions in will make Python set that file as the CWD?
这是一个简单的事情,从我想搜索正则表达式的文件中运行脚本会使Python将该文件设置为CWD吗?
#! python3
# renameDates.py - renames filenames with American MM-DD-YYYY date format
# to European DD-MM-YYYY.
import shutil, os, re
# Create a regex that matches files with the American 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)- # on or two digits for the day
((19|20)\d\d) #four digits for the year
(.*?)$ # all text after the date
""", re.VERBOSE)
# loop over the files in the working directory.
for amerFilename in os.listdir('.'):
mo=datePattern.search(amerFilename)
# Skip files without a date.
if mo==none:
continue
# Get the different parts of the filename.
beforePart=mo.group(1)
monthPart=mo.group(2)
dayPart=mo.group(4)
yearPart=mo.group(6)
afterPart=mo.group(8)
# Form the European-style filename.
euroFilename=beforePart+dayPart+'-'+monthPart+'-'+yearPart+afterPart
# Get the full, absolute file paths.
absWorkingDir=os.path.abspath('.')
amerFilename=os.path.join(absWorkingDir, amerFilename)
euroFilename=os.path.join(absWorkingDir, euroFilename)
# Rename the files.
print('Renaming "%s" to "%s%...' % (amerFilename, euroFilename))
#shutil.move(amerFilename,euroFilename) #uncomment after testing
1 个解决方案
#1
0
Hey do you run your code from Terminal or interpreter? It uses the current working directory. Normaly it's the directory where you have been before starting the script / python interpreter... You can check your current working directory with this code... Hope this helps you:
嘿,你从终端或口译员运行你的代码?它使用当前的工作目录。 Normaly它是您在启动脚本/ python解释器之前的目录...您可以使用此代码检查当前的工作目录...希望这可以帮助您:
import os
print(os.getcwd())
You can change the working directory with:
您可以使用以下命令更改工作目录:
os.chdir(path)
#1
0
Hey do you run your code from Terminal or interpreter? It uses the current working directory. Normaly it's the directory where you have been before starting the script / python interpreter... You can check your current working directory with this code... Hope this helps you:
嘿,你从终端或口译员运行你的代码?它使用当前的工作目录。 Normaly它是您在启动脚本/ python解释器之前的目录...您可以使用此代码检查当前的工作目录...希望这可以帮助您:
import os
print(os.getcwd())
You can change the working directory with:
您可以使用以下命令更改工作目录:
os.chdir(path)