Python has a helper function stat.filemode to go from the st_mode (integer) as reported by os.stat into the familiar "stringy" format (I don't know if this representation has a proper name).
>>> stat.filemode(0o100644)
'-rw-r--r--'
Is there any "unfilemode" helper function to go the other way?
>>> unfilemode('-rw-r--r--')
33188
This is what I tried, but it's producing wrong results. That's not treating the first character denoting file type correctly, and not handling sticky bits etc
table = {
ord('r'): '1',
ord('w'): '1',
ord('x'): '1',
ord('-'): '0',
}
def unfilemode(s):
return int(s.translate(table), 2)
Python is open-source, you can just read the source code for the
statmodule and write the inverse function.See: https://github.com/python/cpython/blob/master/Lib/stat.py#L112
Note that I'm being "naughty" and accessing private members of the
statmodule. The usual caveats apply.Also note that the documentation for
stat.filemodeis incorrect anyway, since0o100000is technically not part of the file mode, it is the file typeS_IFREG. From inode(7):