【问题标题】:Get file attributes (hidden, readonly, system, archive) in Python在 Python 中获取文件属性(隐藏、只读、系统、存档)
【发布时间】:2015-01-27 13:18:57
【问题描述】:

刚开始学习 Python。如何在 Python 中获取文件属性的状态?我知道os.chmod(fullname, stat.S_IWRITE) delete readonly 属性,但是我怎样才能在不改变状态的情况下获得状态呢?我需要得到"hidden""system""readonly""archive"的所有属性

【问题讨论】:

  • 哪个操作系统,例如在 linux 上,隐藏文件是任何以. 作为名称第一个字符的文件,但在 Windows 上,我认为它是一个文件属性。

标签: python attributes operating-system chmod stat


【解决方案1】:

你可以像这样直接使用 Windows API

import win32con
import win32api
attrs = win32api.GetFileAttributes(filepath)
attrs & win32con.FILE_ATTRIBUTE_SYSTEM
attrs & win32con.FILE_ATTRIBUTE_HIDDEN

【讨论】:

  • attrs & 部分有什么作用?
  • FileAttributes 是 flags 整数,所以你需要检查每一位,每一位代表一个布尔值。
  • 那么在得到attr之后,如何从中提取那些隐藏或归档等值呢?
【解决方案2】:

你需要看看模块statos.stat

 os.stat(path)

Perform the equivalent of a stat() system call on the given path. (This function follows symlinks; to stat a symlink use lstat().)

The return value is an object whose attributes correspond to the members of the stat structure, namely:

    st_mode - protection bits,
    st_ino - inode number,
    st_dev - device,
    st_nlink - number of hard links,
    st_uid - user id of owner,
    st_gid - group id of owner,
    st_size - size of file, in bytes,
    st_atime - time of most recent access,
    st_mtime - time of most recent content modification,
    st_ctime - platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)

【讨论】:

  • 隐藏属性在哪里?
【解决方案3】:

如果你使用python 3.4+,你可以使用pathlibstat方法。

from pathlib import Path

print(Path(r"D:\temp\test.txt").stat())

输出:

os.stat_result(
    st_mode=33206, 
    st_ino=204632308068721491, 
    st_dev=67555953, 
    st_nlink=1, 
    st_uid=0, 
    st_gid=0, 
    st_size=4, 
    st_atime=1550757968, 
    st_mtime=1550757968, 
    st_ctime=1550757951
)

here is more information about os.stat_result

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多