Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting last modified for every file in a directory

Tags:

python

I'm trying to get data for every file in a specific directory. Right now I'm just trying to get last-modified date. It seems like I need to convert this WindowsPath to a string, but I couldn't find any function that would do that.

import os
import time
from pathlib import Path

startDir = os.getcwd()

pt = r"\\folder1\folder2"

asm_pths = [pth for pth in Path(pt).iterdir()
            if pth.suffix == '.xml']


for file in asm_pths:
    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
    print("last modified: %s" % time.ctime(mtime))

Console:

Traceback (most recent call last):
  File "C:\Users\daniel.bak\My Documents\LiClipse Workspace\Crystal Report Batch Analyzer\Analyzer\analyzer.py", line 34, in <module>
    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
TypeError: argument should be string, bytes or integer, not WindowsPath
like image 344
Daniel Paczuski Bak Avatar asked Apr 12 '16 12:04

Daniel Paczuski Bak


People also ask

How do you see who last modified a folder?

Every time a user accesses the selected file/folder, and changes the permission on it, an event log will be recorded in the Event Viewer. To view this audit log, go to the Event Viewer. Under Windows Logs, select Security. You can find all the audit logs in the middle pane as displayed below.

How do I find recently modified files?

How to find the date of modified files. Press the Windows key + E on the keyboard to open File Explorer. On the left side-scrolling menu, select the drive or folder that you want to view the last modified date(s) (A) for the contents.

How do I find the last modified date of a file?

lastModified() method: It contains a method called lastModified() which returns the last modified date of a file or directory in form of a long millisecond epoch value, which can be made readable using format() method of SimpleDateFormat class.

Which command gives information about the time of last modification done on file?

It can be done in four ways: Using Stat command. Using date command. Using ls -l command. Using httpie.


1 Answers

You may also use lstat().st_mtime for a WindowsPath (pathlib.Path) object.

Example:

from pathlib import Path

file = Path(r'C:\Users\<user>\Desktop\file.txt')
file.lstat().st_mtime

Output: 1496134873.8279443

import datetime
datetime.datetime.fromtimestamp(file.lstat().st_mtime)

Output: datetime.datetime(2017, 5, 30, 12, 1, 13, 827944)
like image 116
np8 Avatar answered Oct 05 '22 08:10

np8