获取目录中每个文件的最后修改时间

Dan*_*Bak 8 python

我正在尝试获取特定目录中每个文件的数据。现在我只是想获得最后修改日期。似乎我需要将此 WindowsPath 转换为字符串,但我找不到任何可以执行此操作的函数。

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))
Run Code Online (Sandbox Code Playgroud)

安慰:

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
Run Code Online (Sandbox Code Playgroud)

kak*_*dol 7

不需要使用os.stat函数,pathlib 具有相同的函数 -file.stat()其中 file 是路径对象。
您可以使用以下代码:

for file in asm_pths:
    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = file.stat()
    print(f'last modified: {time.ctime(mtime)}')
Run Code Online (Sandbox Code Playgroud)

但如果您只想要最后修改日期,请使用以下命令:

for file in asm_pths:
    print(f'last modified: {time.ctime(file.stat().st_mtime)}')
Run Code Online (Sandbox Code Playgroud)

我宁愿尽可能避免在同一个项目中使用 os.path 和 pathlib.Path ,以防止混淆和错误,因为 pathlib 的路径由 Path 对象组成,而 os.path 期望字符串作为路径。


np8*_*np8 5

您也可以lstat().st_mtime用于WindowsPath(pathlib.Path) 对象。

例子:

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)
Run Code Online (Sandbox Code Playgroud)


sty*_*ane 4

path的参数必须os.stat是字符串,但您传递的是 的实例Path。您需要Path使用 转换为字符串str

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

但如果你只想要最后修改日期那么就os.path.getmtime可以了:

for file in asm_pths:
    print("last modified: %s" % time.ctime(os.path.getmtime(str(file)))
Run Code Online (Sandbox Code Playgroud)

  • 不需要os.stat,pathlib具有相同的功能,并且在Path对象和字符串之间切换可能会令人困惑 (2认同)