For example:
import os
print(os.listdir("path/to/dir"))
will list files in a directory.
How do I get the file modification time for all files in the directory?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When looking for file attributes for all files in a directory, and you are using Python 3.5 or newer, use the
os.scandir()function to get a directory listing with file attributes combined. This can potentially be more efficient than usingos.listdir()and then retrieve the file attributes separately:The
DirEntry.stat()function, when used on Windows, doesn’t have to make any additional system calls, the file modification time is already available. The data is cached, so additionalentry.stat()calls won’t make additional system calls.You can also use the
pathlibmodule Object Oriented instances to achieve the same:On earlier Python versions, you can use the
os.statcall for obtaining file properties like the modification time.st_mtimeis a float value on python 2.5 and up, representing seconds since the epoch; use thetimeordatetimemodules to interpret these for display purposes or similar.Do note that the value’s precision depends on the OS you are using:
If all you are doing is get the modification time, then the
os.path.getmtimemethod is a handy shortcut; it uses theos.statmethod under the hood.Note however, that the
os.statcall is relatively expensive (file system access), so if you do this on a lot of files, and you need more than one datapoint per file, you are better off usingos.statand reuse the information returned rather than using theos.pathconvenience methods whereos.statwill be called multiple times per file.