Directory Navigation
I LOVE DOING THIS :)
Directory details ?
Methods for traversing directories
Listing files and thier information
Creating and Deleting directories + files
Test to check if something is a file or directory
Inorder to perform all this, we'll have to import the os module
Let's quickly write a program to check if a file is actually a file or a directory
os.path.isfile()
andos.path.isdir()
checks for the file or the directory
So, now how do we search for specific kind of files ? How do we grep them ?
Exercise Question
Create a program which takes the path of directory as input and from that directory it checks all the files within it and makes sure if it's really a directory or a file, and prints them in a hierarchical way ?
For any given filename list out all the stats related to the file such as size, creation time, path
os.stat( path )
- Get the status of a file or a file descriptor. Perform the equivalent of a stat()
system call on the given path.
st_size - Size of the file in bytes, if it is a regular file or a symbolic link
st_uid - User identifier of the file owner
import pwd
- This module provides access to the Unix user account and password database
pwd.getpwuid(uid) - Return the password database entry for the given numeric user ID
pw_name - Login name attribute in the pwd module
pw_passwd - Displays the password in an encrypted format
os.path.join("path", "to", "folder")
- It can handle join multiple paths, and take care of the right syntax for the current operating system
os.path.abspath() - This function will convert the relative path to an absolute path by prefixing the current working directory to the path, Basically returns the absolute path of the
sys.argv[1]
Another noob way to perform the above task would be directly calling the methods and attributes
Last updated