[python] 파이썬에서 생성 날짜별로 정렬 된 디렉토리 목록을 어떻게 얻습니까?

디렉토리에있는 모든 파일 목록을 날짜별로 정렬하는 가장 좋은 방법은 무엇입니까? 수정 됨], Windows 컴퓨터에서 Python을 사용합니까?



답변

업데이트 : dirpathPython 3에서 수정 날짜별로 항목 을 정렬 합니다.

import os
from pathlib import Path

paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)

( 더 큰 가시성을 위해 @Pygirl의 대답을 여기에 넣으 십시오)

filenames 목록이 이미있는 경우 filesWindows에서 작성 시간을 기준 으로 해당 파일 을 제자리에 정렬하려면 다음을 수행하십시오.

files.sort(key=os.path.getctime)

예를 들어 @ Jay ‘s answer에glob 표시된대로 사용하여 얻을 수있는 파일 목록입니다 .


오래된 대답은
다음 버전의 자세한 더의 @Greg Hewgill의 대답 . 질문 요구 사항에 가장 적합합니다. 생성 날짜와 수정 날짜를 구분합니다 (적어도 Windows에서는).

#!/usr/bin/env python
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time

# path to the directory (relative or absolute)
dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'

# get all entries in the directory w/ stats
entries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
entries = ((os.stat(path), path) for path in entries)

# leave only regular files, insert creation date
entries = ((stat[ST_CTIME], path)
           for stat, path in entries if S_ISREG(stat[ST_MODE]))
#NOTE: on Windows `ST_CTIME` is a creation date 
#  but on Unix it could be something else
#NOTE: use `ST_MTIME` to sort by a modification date

for cdate, path in sorted(entries):
    print time.ctime(cdate), os.path.basename(path)

예:

$ python stat_creation_date.py
Thu Feb 11 13:31:07 2009 stat_creation_date.py


답변

디렉토리에서 마지막으로 업데이트 된 파일을 확인하기 위해 Python 스크립트에 대해 과거 에이 작업을 수행했습니다.

import glob
import os

search_dir = "/mydir/"
# remove anything from the list that is not a file (directories, symlinks)
# thanks to J.F. Sebastion for pointing out that the requirement was a list 
# of files (presumably not including directories)  
files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))
files.sort(key=lambda x: os.path.getmtime(x))

파일 mtime을 기반으로 원하는 것을 수행해야합니다.

편집 : 원한다면 glob.glob () 대신 os.listdir ()을 사용할 수도 있습니다. 원래 코드에서 glob을 사용한 이유는 glob을 사용하여 특정 세트가있는 파일 만 검색하려고했기 때문입니다. glob ()가 더 적합한 파일 확장자입니다. listdir을 사용하는 방법은 다음과 같습니다.

import os

search_dir = "/mydir/"
os.chdir(search_dir)
files = filter(os.path.isfile, os.listdir(search_dir))
files = [os.path.join(search_dir, f) for f in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x))


답변

os.path.getmtime에포크 이후의 시간 (초)을 제공 하는 기능이 있으며보다 빠릅니다 os.stat.

import os

os.chdir(directory)
sorted(filter(os.path.isfile, os.listdir('.')), key=os.path.getmtime)


답변

내 버전은 다음과 같습니다.

def getfiles(dirpath):
    a = [s for s in os.listdir(dirpath)
         if os.path.isfile(os.path.join(dirpath, s))]
    a.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)))
    return a

먼저 파일 이름 목록을 작성합니다. isfile ()은 디렉토리를 건너 뛰는 데 사용됩니다. 디렉토리를 포함해야하는 경우 생략 할 수 있습니다. 그런 다음 수정 날짜를 키로 사용하여 목록을 적절하게 정렬합니다.


답변

하나의 라이너가 있습니다.

import os
import time
from pprint import pprint

pprint([(x[0], time.ctime(x[1].st_ctime)) for x in sorted([(fn, os.stat(fn)) for fn in os.listdir(".")], key = lambda x: x[1].st_ctime)])

그러면 os.listdir ()을 호출하여 파일 이름 목록을 가져온 다음 각 파일마다 os.stat ()를 호출하여 작성 시간을 얻은 다음 작성 시간을 기준으로 정렬합니다.

이 메소드는 각 파일에 대해 os.stat ()를 한 번만 호출하므로 정렬에서 각 비교에 대해 호출하는 것보다 효율적입니다.


답변

디렉토리를 변경하지 않고 :

import os

path = '/path/to/files/'
name_list = os.listdir(path)
full_list = [os.path.join(path,i) for i in name_list]
time_sorted_list = sorted(full_list, key=os.path.getmtime)

print time_sorted_list

# if you want just the filenames sorted, simply remove the dir from each
sorted_filename_list = [ os.path.basename(i) for i in time_sorted_list]
print sorted_filename_list


답변

파이썬 3.5 이상

from pathlib import Path
sorted(Path('.').iterdir(), key=lambda f: f.stat().st_mtime)