pythonを使用してフォルダーの最新ファイルを取得する必要があります。コードを使用している間:
max(files, key = os.path.getctime)
以下のエラーが発生します:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'
pythonを使用してフォルダーの最新ファイルを取得する必要があります。コードを使用している間:
max(files, key = os.path.getctime)
以下のエラーが発生します:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'
回答:
files変数に割り当てられているものはすべて正しくありません。次のコードを使用します。
import glob
import os
list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file
if os.path.isdir(latest_file):
pathlib.Path文字列とはos.pathよりもオブジェクトより。:pathlib.Pathは、あなたの答えになるオブジェクトを持つ list_of_paths = folder_path.glob('*'); latest_path = max(list_of_paths, key=lambda p: p.stat().st_ctime)
os.path.getctimeでも、キーとして使用できPathます。
max(files, key = os.path.getctime)
かなり不完全なコードです。なにfiles?おそらく、から出てくるファイル名のリストですos.listdir()。
ただし、パスが共通であるため、このリストにはファイル名の部分(別名「ベース名」)のみがリストされています。それを正しく使用するためには、それをそれへの(そしてそれを取得するために使用される)パスと組み合わせる必要があります。
(テストされていない)など:
def newest(path):
files = os.listdir(path)
paths = [os.path.join(path, basename) for basename in files]
return max(paths, key=os.path.getctime)
if basename.endswith('.csv')リスト内包表記に挿入するだけです。
より効率的glob.iglob()であるためglob.glob()、の代わりに使用することをお勧めします。
glob.iglob()実際にすべてを同時に格納せずにglob()と同じ値を生成する反復子を返します。
つまり glob.iglob()、より効率的になります。
私は主に以下のコードを使用して、パターンに一致する最新のファイルを見つけます:
LatestFile = max(glob.iglob(fileNamePattern),key=os.path.getctime)
注:のバリアントがあります max関数のます。最新のファイルを見つける場合は、以下のバリアントを使用します。
max(iterable, *[, key, default])
これは反復可能である必要があるため、最初のパラメーターは反復可能でなければなりません。numの最大値を見つける場合、beowバリアントを使用できます。max (num1, num2, num3, *args[, key])
max()種が好きです。私の場合、key=os.path.basenameファイル名にタイムスタンプが含まれているため、別のものを使用しました。
私はコメントする評判がありませんが、Marlon Abeykoons応答からのctimeは正しい結果を与えませんでした。ただし、mtimeを使用するとうまくいきます。(key = os.path.get m time))
import glob
import os
list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getmtime)
print latest_file
その問題について2つの答えが見つかりました。
python os.path.getctime maxがpythonの最新の 違いを返さない-UNIXシステムでのgetmtime()とgetctime()
(回答を改善するために編集)
最初に関数get_latest_fileを定義します
def get_latest_file(path, *paths):
fullpath = os.path.join(path, paths)
...
get_latest_file('example', 'files','randomtext011.*.txt')
docstringを使用することもできます!
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
Python 3を使用している場合は、iglobを使用できます代わりに。
最新のファイルの名前を返す完全なコード:
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
files = glob.glob(fullpath) # You may use iglob in Python3
if not files: # I prefer using the negation
return None # because it behaves like a shortcut
latest_file = max(files, key=os.path.getctime)
_, filename = os.path.split(latest_file)
return filename
JuniperAccessLog-standalone-FCL_VPNから手に入れたのですか?
上記の提案を使用しようとしたところ、プログラムがクラッシュしました。特定しようとしているファイルが使用されていることがわかり、 'os.path.getctime'を使用しようとするとクラッシュしました。最終的に私のために働いたのは:
files_before = glob.glob(os.path.join(my_path,'*'))
**code where new file is created**
new_file = set(files_before).symmetric_difference(set(glob.glob(os.path.join(my_path,'*'))))
このコードは、2つのファイルリストのセットの間で一般的でないオブジェクトを取得します。これは、最もエレガントではありません。同時に複数のファイルが作成された場合、おそらく安定しません。
Windowsでのはるかに高速なメソッド(0.05秒)は、これを行うbatスクリプトを呼び出します。
get_latest.bat
@echo off
for /f %%i in ('dir \\directory\in\question /b/a-d/od/t:c') do set LAST=%%i
%LAST%
どこ \\directory\in\questionあなたが調査したいディレクトリです。
get_latest.py
from subprocess import Popen, PIPE
p = Popen("get_latest.bat", shell=True, stdout=PIPE,)
stdout, stderr = p.communicate()
print(stdout, stderr)
ファイルstdoutが見つかった場合はパスであり、stderrあり、Noneです。
使用するstdout.decode("utf-8").rstrip()ファイル名の使用可能な文字列表現を取得します。
ls -Art | tail -n 1。ソリューションについて主張する前に、ソリューションのパフォーマンスを評価してください。