90 likes | 305 Views
Files and Directory Manipulation. CSIS 1595: Fundamentals of Programming and P roblem Solving 1. OS Module. Commands for manipulating files and directories Similar to Unix syntax import os required Example: Directory commands os.getcwd () Returns string with current path
E N D
Files and Directory Manipulation CSIS 1595: Fundamentals of Programming and Problem Solving 1
OS Module • Commands for manipulating files and directories • Similar to Unix syntax • import osrequired • Example: Directory commands • os.getcwd()Returns string with current path • os.chdir(path) Move to directory path • Absolute path or relative path (or .. for parent directory)
File Manipulation • os.listdir()Returns list of strings with names of all files/subdirectories in current directory • os.path.isfile(“filename”)Returns true if filename is a file in the current directory • os.path.isdir(“dirname”)Returns true if dirnameis a file in the current directory
Uses for Validation • Can check whether file exists before openingif os.path.isfile(filename):… • Not a substitute for exception handling(file may exist but still not be readable) • Can use to check whether file already exists before overwriting it • Verify with user
Navigation Example • Can create file navigation tool • List all files/directories and prompt user for selection • If file open it, or if directory navigate to it