При работе с файлами в Python часто необходимо получить дату последнего изменения файла. Эта информация может быть полезна для различных целей, например для отслеживания изменений, организации файлов или выполнения условных операций. В этой статье мы рассмотрим несколько методов получения даты последнего изменения файла в Python, а также примеры кода. Давайте погрузимся!
Метод 1: использование модуля os.path
import os.path
import time
file_path = 'path/to/your/file'
# Retrieve the last modification time as a timestamp
timestamp = os.path.getmtime(file_path)
# Convert the timestamp to a readable format
modification_date = time.ctime(timestamp)
print(f"The last modification date of the file is: {modification_date}")
Метод 2: использование функции os.stat
import os
import time
file_path = 'path/to/your/file'
# Retrieve the file's status information
stat_info = os.stat(file_path)
# Extract the last modification time from the status information
modification_date = time.ctime(stat_info.st_mtime)
print(f"The last modification date of the file is: {modification_date}")
Метод 3: использование модуля pathlib
(Python 3.4+)
from pathlib import Path
import time
file_path = Path('path/to/your/file')
# Retrieve the last modification time as a timestamp
timestamp = file_path.stat().st_mtime
# Convert the timestamp to a readable format
modification_date = time.ctime(timestamp)
print(f"The last modification date of the file is: {modification_date}")
Метод 4. Использование модуля datetime
import datetime
import os.path
file_path = 'path/to/your/file'
# Retrieve the last modification time as a timestamp
timestamp = os.path.getmtime(file_path)
# Convert the timestamp to a datetime object
modification_date = datetime.datetime.fromtimestamp(timestamp)
print(f"The last modification date of the file is: {modification_date}")
Метод 5: использование модуля subprocess
(только для Linux/Mac)
import subprocess
file_path = 'path/to/your/file'
# Retrieve the last modification date using the 'stat' command
result = subprocess.run(['stat', '-c', '%y', file_path], capture_output=True, text=True)
# Extract the modification date from the command output
modification_date = result.stdout.strip()
print(f"The last modification date of the file is: {modification_date}")
В этой статье мы рассмотрели различные методы получения даты последнего изменения файла в Python. Мы рассмотрели методы использования таких модулей, как os.path
, os.stat
, pathlib
, datetime
и даже 14.модуль для систем Linux и Mac. В зависимости от ваших конкретных требований и версии Python вы можете выбрать наиболее подходящий метод. Используя эти методы, вы можете легко получить дату последнего изменения любого файла в ваших приложениях Python.
, os.stat
, pathlib
, datetime
, subprocess