2017-05-11 1 views
0

私はPythonには全く新しいです。年、月、日で文字列を並び替えよう

基本問題: がディレクトリから

私は、最新のBAKを検索するスクリプトを書いているの年、月、日によってファイル名のソートされたリストを抽出し

ファイルディレクトリとインポートそれをデータベースに保存します。

MyDB_05-09-2017.bak 

MyDB_05-10-2017.bak 

は、私はファイル名で、最新のBAKファイルを解凍したい:

ファイルは次の形式を持っています。

年、月、日でファイルを並べ替える必要があります。

import glob,os,re 
from datetime import datetime 

# SQL server backup directory 
os.chdir('C:\\SQLServerBackups') 

# invoke the sql script to drop the database if exists 
os.system('C:\\SQLServerBackups\\database_sql_scripts\\drop_database.bat') 

# find the latest .bak file and rename it to target 

file_list = glob.glob('*.bak') 
latest_bak_file = file_list[0] 
latest_year = 0 
latest_month = 0 
latest_day = 0 

for file in file_list: 
    print(file) 
    del_list = re.split('[-._]',file) 
    temp_latest_year = int(del_list[3]) 
    temp_latest_month = int(del_list[1]) 
    temp_latest_day = int(del_list[2]) 

    if temp_latest_year > latest_year: 
     latest_year = temp_latest_year 
     latest_month = temp_latest_month 
     latest_day = temp_latest_day 
    elif temp_latest_year == latest_year: 
     if temp_latest_month > latest_month: 
      latest_month = temp_latest_month 
      latest_day = temp_latest_day 
     elif temp_latest_month == latest_month: 
      if temp_latest_day > latest_day: 
       latest_day = temp_latest_day 
       latest_bak_file = file 

print(latest_bak_file) 

私はそれをよりよく実現することができる方法上の任意のアドバイスを:

は、これは私が試してみましたいくつかの基本的な実装ですか?

ファイル名のソートされたリストを年、月、日で作成したいと考えています。

+3

そうですが、組み込みの '' sorted'(https://docs.python.org/3/library/functions.html#sorted)関数があります –

+0

私はPythonには本当に新しいと私は言っている私はその機能を使用できるかどうかを試しましたが、この状況でどのように使用するか分かりません。 この関数をもう一度見て、それをより良く実装する方法を見てみましょう... –

+2

datetime: 'datetime.strptime( 'MyDB_05-09-2017.bak'、 'MyDB_%d-%m-%Y.bak ') ' –

答えて

2

あなたはちょうどあなたがソートするフィールドを返すソートキーの機能を定義することができます@Klaus Dは、検索キーにdatetime.strptimeを使用し、言ったように

import re 

fnames = [ 
    "MyDB_05-10-2017.bak", 
    "MyDB_05-09-2017.bak", 
] 

def sortkey(x): 
    parts = re.split('[-._]', x) 
    return [int(parts[3]), int(parts[1]), int(parts[2])] 

sorted_fnames = sorted(fnames, key=sortkey) 

か、を:

sorted_fnames = sorted(fnames, key=lambda x: datetime.datetime.strptime(x, 'MyDB_%d-%m-%Y.bak')) 
+0

さて、それはうまくトリックを行うことができます!ありがとう! 私はそれを実装しようとし、それが動作するかどうかを確認しようとします。 –

関連する問題