문제

날짜별로 정렬 된 디렉토리에서 모든 파일 목록을 가져 오는 가장 좋은 방법은 무엇입니까? Windows 시스템에서 Python을 사용하여 수정 되었습니까?

도움이 되었습니까?

해결책

여기에 더 많은 장점이 있습니다 @Greg Hewgill대답. 질문 요구 사항에 가장 준수합니다. 생성과 수정 날짜 (적어도 창에서)를 구별합니다.

#!/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 = filter(os.path.isfile, glob.glob(search_dir + "*"))
files.sort(key=lambda x: os.path.getmtime(x))

파일 MTime을 기준으로 원하는 작업을 수행해야합니다.

편집하다: Glob.glob () 대신 OS.ListDir ()를 사용할 수 있습니다. 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))

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

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 ()은 디렉토리를 건너 뛰는 데 사용됩니다. 디렉토리가 포함되어 있으면 생략 할 수 있습니다. 그런 다음 수정 날짜를 키로 사용하여 목록을 현장에서 정렬합니다.

있습니다 os.path.getmtime 에포크 이후 몇 초를 제공하고 os.stat.

import os 

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

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

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

날짜 순서 (Python 3)의 특정 확장자가있는 파일을 읽으려면 필터없이 Glob를 사용하는 내 대답은 다음과 같습니다.

dataset_path='/mydir/'   
files = glob.glob(dataset_path+"/morepath/*.extension")   
files.sort(key=os.path.getmtime)

파이썬에서 3.5+

from pathlib import Path
sorted(Path('.').iterdir(), key=lambda f: f.stat().st_mtime)
sorted(filter(os.path.isfile, os.listdir('.')), 
    key=lambda p: os.stat(p).st_mtime)

당신은 사용할 수 있습니다 os.walk('.').next()[-1] 필터링 대신 os.path.isfile, 그러나 그것은 목록에 죽은 Symlinks를 남기고 os.stat 그들에게 실패 할 것입니다.

이것은 학습을위한 기본 단계입니다.

import os, stat, sys
import time

dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'

listdir = os.listdir(dirpath)

for i in listdir:
    os.chdir(dirpath)
    data_001 = os.path.realpath(i)
    listdir_stat1 = os.stat(data_001)
    listdir_stat2 = ((os.stat(data_001), data_001))
    print time.ctime(listdir_stat1.st_ctime), data_001

Alex Coventry의 답변은 파일이 존재하지 않는 파일의 심볼릭 링크 인 경우 예외가 발생합니다. 다음 코드는 해당 답변을 수정합니다.

import time
import datetime
sorted(filter(os.path.isfile, os.listdir('.')), 
    key=lambda p: os.path.exists(p) and os.stat(p).st_mtime or time.mktime(datetime.now().timetuple())

파일이 존재하지 않으면 이제 ()가 사용되며 심포 링크는 목록의 끝까지 이동합니다.

다음은 확장을 찾고 정렬 옵션을 제공하는 간단한 커플 라인입니다.

def get_sorted_files(src_dir, regex_ext='*', sort_reverse=False): 
    files_to_evaluate = [os.path.join(src_dir, f) for f in os.listdir(src_dir) if re.search(r'.*\.({})$'.format(regex_ext), f)]
    files_to_evaluate.sort(key=os.path.getmtime, reverse=sort_reverse)
    return files_to_evaluate

어쩌면 쉘 명령을 사용해야 할 수도 있습니다. UNIX/Linux에서는 정렬로 파이프를 찾으면 원하는 것을 할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top