2017-03-09 2 views
0

Ich arbeite durch das RenameDates-Projekt in Automate the Boring Zeug. Es soll Datumsangaben nach amerikanischem Muster abgleichen und in europäisches Format umwandeln.Muss ich mein aktuelles Arbeitsverzeichnis immer in Python angeben?

Die Sache, die ich nicht über diesen Code verstehe, ist, wie findet es das richtige Verzeichnis?

Ich kann keinen Code finden, der das aktuelle Arbeitsverzeichnis auf die Datei setzt, in der ich arbeiten muss, aber das Skript scheint geschrieben zu haben, dass das Standardarbeitsverzeichnis dort ist, wo es funktionieren sollte.

Ist es etwas Einfaches wie, das Ausführen des Skripts aus der Datei, die ich nach regulären Ausdrücken suchen möchte, macht Python diese Datei als CWD festlegen?

#! 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 

Antwort

0

Hey, führen Sie Ihren Code von Terminal oder Interpreter? Es verwendet das aktuelle Arbeitsverzeichnis. Normalerweise ist es das Verzeichnis, in dem Sie das Skript/Python vor dem Start Dolmetscher gewesen sein ... Sie können Ihr aktuelles Arbeitsverzeichnis mit diesem Code überprüfen ... Hoffe, das hilft Ihnen:

import os 
print(os.getcwd()) 

Sie können das Arbeitsverzeichnis ändern mit :

os.chdir(path) 
Verwandte Themen