Python st mtime stat

Python File Stat()

Python’s OS module offers a set of methods that enable the users to interact with their computer’s operating system. The OS module is classified with Python’s other basic utility modules. This module offers a portable approach to making use of functionality that is dependent on the operating system. One such example is the stat() module of Python which is used to acquire all of the information on a file or folder. It works by performing a stat system call on the specified path. It gives a variety of information like the inode number, the size, the number of hard links, the time it was created and updated, and a great deal more. The stat module includes constants and methods to interpret the output of the os. stat(), os. fstat(), and os. fstat() functions.

The syntax for the stat method is as follows:

>> os.state(path)

Here, the “path” is complete. A path that may be represented as either a text or a bytes object for which we want to get the information or status.

This function returns a “stat_result” object of type “os.stat_result” that describes the path’s status. The returned “stat_result” object contains the following properties:

  • St_mode: It represents the file type and the file mode bits (permissions).
  • St_ino: On Unix, it represents the inode number. But on Windows, it represents the file index.
  • St_dev: This is the device identification for which this file is stored.
  • The number of hard links is represented by st_nlink.
  • St_uid: This is the file owner’s user identity.
  • St_gid: This is the file owner’s group identity.
  • St_size: This variable reflects the file’s size in bytes.
  • St_atime: This is the most recent access time. It is measured in seconds.
  • St_mtime: This is the time of the most recent content modification. It is measured in seconds.
  • St_ctime: On Unix, it reflects the time of the most recent metadata modification. Whereas on Windows, it represents the time of creation. It is measured in seconds.
  • St_atime ns: The same as st_atime, except the time is given as an integer in nanoseconds.
  • St_mtime ns: The same as st_mtime, but the time is given as an integer in nanoseconds.
  • St_ctime ns: The same as st ctime, but the time is given as an integer in nanoseconds.
  • St_blocks: The number of 512-byte blocks allocated to the file.
  • If the device is an inode, it is represented by st_rdev.
  • St_flags: It represents the file’s user-defined flags.
Читайте также:  Java получить размерности двумерного массива

Note: Some attributes are platform dependent and may not be available.
In this article, we are going to have a look at some Python code as well as some examples of the stat() module that Python offers.

Example 1:

It is a very basic example in which we are going to specify a file to the os.stat() method to obtain the file’s status or all related details.v

In the first line, a file’s path is stored in the variable named “file_path”. Then, the os.stat() method is called with the file path as its parameter. It returns the status of the object file_path and is stored in the new variable named “stats”. The retrieved file status or details is then demonstrated at the output side using the publish directive, as seen in the following snippet:

Example 2:

We can see in the previous example that the os.stat() returns all of the information in one go. This can be very cumbersome and confusing at times especially when we just need some specific information only. In this example, only the limited attributes of the file are displayed.

In the code provided, three modules are imported in Python – os, stat, and time. In the next line, the os.stat() method is called with a file path in its parameter. It creates a “stats_result” object which provides the status of the file containing all of the information and attributes of that file. Then, 3 attributes are called with the format of “time.ctime” which are displayed at the output terminal using the print command. First, “st_atime” is displayed. Then, “st_mtime”. And finally, “st_ctime” as shown in the following screenshot:

Example 3:

Similarly, in this example, the st_mode attribute of the file is displayed which denotes the type of file and the mode bits of the file (permissions).

In the first step, the os module and stat module are imported into Python. In the next line, a file path is passed to the os.stat() method that returns the file’s condition, which includes all of the file’s details. This is stored in the variable named “s”. To display the mode bits, “stat.ST_MODE” is called for objects (which contain the os status of the file). This gets back the file’s mode bits, which are then demonstrated using the publish directive at the output node as seen in the following snapshot:

Example 4:

Another very useful method of stat is to return the size of the file. Let’s see how to grab the file length in Python by utilizing the os stat package.

In Python, the first step is to acquire the os and stat modules. Following that, a file path is passed to the characteristics of the os.stat() method which returns the status of that file along with all of its attributes. This is stored in the variable named “stats”. To get the size of the file, only the stat.ST_SIZE is called for the “stats” object and is stored in the “a” variable. The print command is then used to show it at the output interface, as demonstrated in the following snapshot as well. In this scenario, the document is 4 bytes in size:

Example 5:

We can use this module to find the type of file as well because it has several functions that act as a check for the type of file. In this example, multiple methods of this module are tested to predict the type of file in a Python program.

In this first attempt, we will use the multiple if-check statement where we use the ISDIR method, ISREG method, and the ISLINK method which look for a directory or a Regular file or even for a link, respectively. In this attempt, we have given the path of a normal text file and we get the print statement of the if block where the condition for the regular file becomes true, as seen in the following snippet:

Now, we will use the same blocks of the IF statements and check these methods to verify whether they can detect a link in place of the file’s path as the parameter.

In this attempt, we gave a link to a website in the stat function and passed it into the parameter of several other functions. The print statement in the ISLINK function’s if block which is true in this situation as we can see in the following output:

Conclusion

The OS stat module is a very helpful tool and can be used in many use cases. If you’re writing to a file and wants to see if any changes have been made, you may look at the last modified time. You may also directly verify the file size from your code. There are more applications, but they are more sophisticated and must be considered in light of the situation at hand. This article should help you comprehend how the os stat module works in Python.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

Источник

stat — Interpreting stat() results¶

The stat module defines constants and functions for interpreting the results of os.stat() , os.fstat() and os.lstat() (if they exist). For complete details about the stat() , fstat() and lstat() calls, consult the documentation for your system.

Changed in version 3.4: The stat module is backed by a C implementation.

The stat module defines the following functions to test for specific file types:

Return non-zero if the mode is from a directory.

Return non-zero if the mode is from a character special device file.

Return non-zero if the mode is from a block special device file.

Return non-zero if the mode is from a regular file.

Return non-zero if the mode is from a FIFO (named pipe).

Return non-zero if the mode is from a symbolic link.

Return non-zero if the mode is from a socket.

Return non-zero if the mode is from a door.

Return non-zero if the mode is from an event port.

Return non-zero if the mode is from a whiteout.

Two additional functions are defined for more general manipulation of the file’s mode:

Return the portion of the file’s mode that can be set by os.chmod() —that is, the file’s permission bits, plus the sticky bit, set-group-id, and set-user-id bits (on systems that support them).

Return the portion of the file’s mode that describes the file type (used by the S_IS*() functions above).

Normally, you would use the os.path.is*() functions for testing the type of a file; the functions here are useful when you are doing multiple tests of the same file and wish to avoid the overhead of the stat() system call for each test. These are also useful when checking for information about a file that isn’t handled by os.path , like the tests for block and character devices.

import os, sys from stat import * def walktree(top, callback): '''recursively descend the directory tree rooted at top, calling the callback function for each regular file''' for f in os.listdir(top): pathname = os.path.join(top, f) mode = os.lstat(pathname).st_mode if S_ISDIR(mode): # It's a directory, recurse into it walktree(pathname, callback) elif S_ISREG(mode): # It's a file, call the callback function callback(pathname) else: # Unknown file type, print a message print('Skipping %s' % pathname) def visitfile(file): print('visiting', file) if __name__ == '__main__': walktree(sys.argv[1], visitfile) 

An additional utility function is provided to convert a file’s mode in a human readable string:

Convert a file’s mode to a string of the form ‘-rwxrwxrwx’.

Changed in version 3.4: The function supports S_IFDOOR , S_IFPORT and S_IFWHT .

All the variables below are simply symbolic indexes into the 10-tuple returned by os.stat() , os.fstat() or os.lstat() .

Number of links to the inode.

Size in bytes of a plain file; amount of data waiting on some special files.

Time of last modification.

The “ctime” as reported by the operating system. On some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time (see platform documentation for details).

The interpretation of “file size” changes according to the file type. For plain files this is the size of the file in bytes. For FIFOs and sockets under most flavors of Unix (including Linux in particular), the “size” is the number of bytes waiting to be read at the time of the call to os.stat() , os.fstat() , or os.lstat() ; this can sometimes be useful, especially for polling one of these special files after a non-blocking open. The meaning of the size field for other character and block devices varies more, depending on the implementation of the underlying system call.

The variables below define the flags used in the ST_MODE field.

Use of the functions above is more portable than use of the first set of flags:

Источник

Оцените статью