import os
 
def main():
 
  # Print the name of the OS
  print os.name;  
 
if __name__ == "__main__":
  main()

12.2 Check for item existence and type

N.B. textfile.txt must exist for the following...

import os
from os import path
 
def main():
 
  # Check for item existence and type
  print "Item exists: " + str(path.exists("textfile.txt"))
  print "Item is a file: " + str(path.isfile("textfile.txt"))
  print "Item is a directory: " + str(path.isdir("textfile.txt"))
 
if __name__ == "__main__":
  main()

The path class has several methods which take a file as an argument and return information about the file.

12.3 Work with file paths

import os
from os import path
 
def main():
 
  # Work with file paths
  print "Item's path: " + str(path.realpath("textfile.txt"))
  print "Item's path and name: " + str(path.split(path.realpath("textfile.txt")))
 
if __name__ == "__main__":
  main()

Call .realpath("textfile.txt") to get the file path

Call .split() on theoutput of .realpath() to get an array consisting of the "item's path" and the "filename". So, the filename is "split" off of the path and you get them separately, that's handy...

This path output is run through the string method str() of Python so it can be concatenated with other string text.

12.4 Get the modification time

from os import path
import datetime
from datetime import time
import time
 
def main():
 
    # Get the modification time
    modtime = time.ctime(path.getmtime("textfile.txt"))
    print modtime
    # Get it as a datetime format instead of a ctime format
    print datetime.datetime.fromtimestamp(path.getmtime("textfile.txt"))
 
if __name__ == "__main__":
    main()

Call path.getmtime("textfile.txt") on the path to the file

The time class's ctime method time.ctime() is used to convert the output into a readable time.

12.5 Calculate how long ago the item was modified

from os import path
import datetime
from datetime import date, time
import time
 
def main():
 
    # Calculate how long ago the item was modified
    timediff = datetime.datetime.now(
    ) - datetime.datetime.fromtimestamp(path.getmtime("textfile.txt"))
    print "It has been " + str(timediff) + " minutes since the file was modified"
    print "Or, " + str(timediff.total_seconds()) + " seconds"
 
if __name__ == "__main__":
    main()