2016-09-14 113 views
0

創建腳本,該腳本將自動處理當天的文件路徑,執行一些操作,然後保存到同一目錄。基於日期的Python文件路徑

文件夾結構是基於日期:

maindir - >year - >month - >當月文件。

到目前爲止,我的做法是:

year = time.strftime("%Y") 
month = time.strftime("%B") 
dir = parse('C:\maindir' + '\' + str(year) + '\' + str(month)) 
os.chdir(dir) 

不過,我想我去os.makedirs重用此之後,以使文件夾結構會自動生成。

或者這將是更好地使這解析目錄路徑,以便我可以調用一個方法,如:

if not os.path.exists(method): 
    try: 
     os.makedirs(os.path.dirname(method)) 

更新:

偶然發現這個討論這幫助了很多 - constructing absolute path with os.join()

netdrive="\\network.com\mainfolder$" 
year = time.strftime("%Y") 
month = time.strftime("%B") 
path=path.abspath(path.join(os.sep,netdrive,year,month)) 
if not os.path.exists(path): 
    os.makedirs(path) 
os.chdir(path) 

所以,我與這一些進展 - 但是,現在我有recogn的問題根據當前的網絡驅動器使用C:/默認值作爲path.abspath的一部分。如何將它重寫到一個新的根驅動器,與驅動器的映射無關? D:/爲一個用戶,E:/秒 - 等

回答

1

由於路徑只包含年和月,該目錄將平均保持相同連續30天。

因此,最好在創建它之前檢查目錄是否已經存在。

if not os.path.exists(directory): 
    os.makedirs(directory)