Evgeny Gerbut
Evgeny Gerbut

Reputation: 390

Get file attributes (hidden, readonly, system, archive) in Python

Just started learning Python. How can i get a status of file's attributes in Python? I know that os.chmod(fullname, stat.S_IWRITE) delete readonly attribute, but how can i get status without changing it? I need to get all of the attributes of "hidden", "system", "readonly", "archive"

Upvotes: 9

Views: 14321

Answers (4)

Ricardo
Ricardo

Reputation: 89

Since Python 3.5, os.stat(), os.fstat() and os.lstat() returns a class os.stat_result that, on Windows systems, includes st_file_attributes. You can use the FILE_ATTRIBUTE_* constants in the stat module to check the file attributes.

File attributes

>attrib test.txt
A    R               C:\test.txt

Sample code

import os
import stat

fn   = "test.txt"
info = os.stat(fn)
print("Attributes of", fn)
if info.st_file_attributes & stat.FILE_ATTRIBUTE_ARCHIVE:  print(" - archive")
if info.st_file_attributes & stat.FILE_ATTRIBUTE_SYSTEM:   print(" - system")
if info.st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN:   print(" - hidden")
if info.st_file_attributes & stat.FILE_ATTRIBUTE_READONLY: print(" - read only")

Output

Attributes of test.txt
 - archive
 - read only

Upvotes: 1

Vlad Bezden
Vlad Bezden

Reputation: 89527

If you are using python 3.4+ you can use pathlib stat method.

from pathlib import Path

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

Output:

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

Upvotes: 3

loopingz
loopingz

Reputation: 1209

You can use directly the Windows API like that

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

Upvotes: 9

Hackaholic
Hackaholic

Reputation: 19733

you need to take a look at module stat and os.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)

Upvotes: 5

Related Questions