Python Programming – Python Directory Methods

In the previous section, we have described various Python directory handling methods with the programming illustration of each. However, Python contains a large number of methods to be work with the directories. All these methods are to be used with the os module. That means the os module needs to be imported for using any of the methods associated with directories. The list of methods to be used with directories is given in Table 9.6. with the description of each method.

Method Description
os.access(path, mode) Uses the real uid/gid to test for access to path.
os.chdir(path) Changes the current working directory to path
os.chflags(path, flags) Sets the flags of path to the numeric flags.
os.chmod(path, mode) Changes the mode of path to the numeric mode.
os.chown(path, uid,gid) Changes the owner and group id of path to the numeric uid and gid.
os.chroot(path) Changes the root directory of the current process to path.
os.close(fd) Closes file descriptor fd
os.closerange(fd_low, fd_high) Closes all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors.
os.dup(fd) Returns a duplicate of file descriptor fd.
os.dup2(fd, fd2) Duplicates file descriptor fd to fd2, closing the latter first if necessary.
os.fchdir(fd) Changes the current working directory to the directory represented by the file descriptor fd.
os.fchmod(fd, mode) Changes the mode of the file given by fd to the numeric mode.
os.fchown(fd, uid, gid) Changes the owner and group id of the file given by fd to the numeric uid and gid.
os.fdatasync(fd) Forces write of file with filedescriptorfd to disk.
os.getcwd() Returns a string representing the current working directory.
os.getcwdu() Returns a Unicode object representing the current working directory., dst) Creates a hard link pointing to src named dst.
os.listdir(path) Returns a list containing the names of the entries in the directory given by path.
os.lseek(fd, pos, how) Sets the current position of file descriptor fd to position pos, modified by how.
os.major(device) Extracts the device major number from a raw device number.
os.minor(device) Extracts the device minor number from a raw device number.
os.mkdir(path[, mode]) Creates a directory named path with numeric mode mode.
os.remove(path) Removes the file path.
os.renames(old, new) Recursive directory or file renaming function.
os.rmdir(path) Removes the directory path
os.rename(src, dst) Renames the file or directory src to dst., n) Reads at most n bytes from file descriptor fd. Return a string containing the bytes read. If the end of the file referred to by fd has been reached, an empty string is returned.
os.write(fd, str) Writes the string str to file descriptor fd. Return the number of bytes actually written.
Note: All these methods are used with the os module, e.g. os.rmdir().


Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *