2017-03-09 47 views
0

我正在通過在自動化鑽孔東西renameDates項目。它應該符合美國方式的日期,並將它們改爲歐洲格式。我是否總是需要在Python中指定我當前的工作目錄?

我不明白這個代碼的事情是,它是如何找到正確的目錄?

我找不到任何代碼將當前工作目錄設置爲我需要它工作的文件,但腳本似乎是在假設默認當前工作目錄是它的工作目錄的情況下編寫的。

這是簡單的,從文件運行腳本我想搜索正則表達式將使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 

回答

0

嘿,你從終端或口譯員運行你的代碼?它使用當前的工作目錄。 Normaly它就是你已經啓動腳本/ Python解釋器之前所在的目錄...您可以使用此代碼檢查你當前的工作目錄...希望這可以幫助你:

import os 
print(os.getcwd()) 

你可以改變工作目錄:

os.chdir(path) 
相關問題