[英]How to return the modified date for specific file types within a path in Python?
我有一個文件路徑,我需要返回其中的文件名列表 + Python 中每個文件的最后修改日期。我能夠做到這一點,除了問題是我只想對 PDF 執行此操作並且有多個我正在使用的文件夾中的文件類型。 我已經到了可以獲取文件名和修改日期的地步,但是當我嘗試輸入 PDF 唯一規定時遇到錯誤。
以下是我到目前為止所擁有的:
path = <insert path>
def ts_to_dt(ts):
return datetime.datetime.fromtimestamp(ts)
for file in os.scandir(path):
#if file.endswith(".pdf"):
print(file.name, ts_to_dt(file.stat().st_atime))
當我嘗試使用被注釋掉的行執行時(if file.endswith(".pdf")),我得到這個錯誤:
if file.endswith(".pdf"):
^^^^^^^^^^^^^
AttributeError: 'nt.DirEntry' object has no attribute 'endswith'
我是 Python 的新手,所以我們將不勝感激!
我建議為此使用pathlib 。
你可以這樣做:
from pathlib import Path
def print_access_times(path):
path = Path(path) # If path was either a str or Path object, this will work
for file in path.iterdir():
if file.suffix == '.pdf':
print(file.name, ts_to_dt(file.stat().st_atime))
您的代碼的問題是os.scandir
產生DirEntry對象(沒有endswith
方法),而不是字符串。 pathlib 中的Path
對象為pathlib
中的路徑提供了一個更一致的接口。
您可以將file.name.endswith('.pdf')
與os.scandir
解決方案一起使用。
要將路徑 object 轉換回字符串,您可以使用file.as_posix()
或str(file)
。
如果您事先不確定給定路徑是否為目錄,則可以使用以下內容來優雅地處理可能引發的錯誤:
def print_access_times(path):
path = Path(path) # If path was either a str or Path object, this will work
try:
for file in path.iterdir():
if file.suffix == '.pdf':
print(file.name, ts_to_dt(file.stat().st_atime))
except NotADirectoryError:
pass
os.scandir
返回一個os.DirEntry
對象的迭代器,正如您從錯誤消息中看到的那樣。
os.DirEntry
具有您可以獲得的不同屬性,包括一個name
屬性,它是一個字符串。
所以你可以這樣做:
if file.name.endswith(".pdf"):
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.