Python OS Path

The example code below shows how to manipulate Python os path.

#
# Python OS path examples
#
import os
from os import path
import datetime
from datetime import date, time, timedelta
import time


def main():
  # Print the name of the OS
  print(os.name)

  print("Items exists: " + str(path.exists("textfile.txt")))
  print("Itrm s a file: " + str(path.isfile("textfile.txt")))
  print("Itrm s a directory: " + str(path.isdir("textfile.txt")))

  # Work with file paths
  print("Item path: " + str(path.realpath("textfile.txt")))
  print("Item path and name: " + str(path.realpath("textfile.txt")))

  # Get the modification time
  t = time.ctime(path.getmtime("textfile.txt"))
  print("Last modified", t)
  print("Last modified", datetime.datetime.fromtimestamp(path.getmtime("textfile.txt")))

  # Calculate how long ago the item was modified
  td = datetime.datetime.now() - datetime.datetime.fromtimestamp(path.getmtime(("textfile.txt")))
  print("It has been " + str(td) + " since the file was last modified.")
  print("Or, " + str(td.total_seconds()) + " seconds")

if __name__ == "__main__":
  main()


-------------------------------------------------------------------------------
#Output
nt
Items exists: True
Itrm s a file: True
Itrm s a directory: False
Item path: C:\Users\Ronsoft\IdeaProjects\Python\Exercise Files\Ch4\textfile.txt
Item path and name: C:\Users\Ronsoft\IdeaProjects\Python\Exercise Files\Ch4\textfile.txt
Last modified Sat Apr 20 21:16:34 2019
Last modified 2019-04-20 21:16:34.862068
It has been 10:57:20.218993 since the file was last modified.
Or, 39440.218993 seconds

Comments

Popular posts from this blog

How to write to a file in Kotlin

Python Tkinter example