Python3 OS File/Directory Methods
The os module is an important module in Python’s standard library. It provides functions for interacting with the operating system.
Through the os module, you can perform file operations, directory operations, environment variable management, process management, and other tasks.
The os module is cross-platform, meaning you can use the same code on different operating systems (such as Windows, Linux, macOS).
Before using the os module, you need to import it first. The code to import the os module is as follows:
Common Features of the os Module
Section titled “Common Features of the os Module”1. Get the Current Working Directory
Section titled “1. Get the Current Working Directory”The os.getcwd() function is used to get the path of the current working directory. The current working directory is the directory where the Python script is executing.
Example
Section titled “Example”2. Change the Current Working Directory
Section titled “2. Change the Current Working Directory”The os.chdir(path) function is used to change the current working directory. path is the directory path you want to switch to.
Example
Section titled “Example”3. List Directory Contents
Section titled “3. List Directory Contents”The os.listdir(path) function is used to list all files and subdirectories in the specified directory. If the path parameter is not provided, it defaults to listing the contents of the current working directory.
Example
Section titled “Example”4. Create a Directory
Section titled “4. Create a Directory”The os.mkdir(path) function is used to create a new directory. If the directory already exists, a FileExistsError exception will be thrown.
Example
Section titled “Example”5. Delete a Directory
Section titled “5. Delete a Directory”The os.rmdir(path) function is used to delete an empty directory. If the directory is not empty, an OSError exception will be thrown.
Example
Section titled “Example”6. Delete a File
Section titled “6. Delete a File”The os.remove(path) function is used to delete a file. If the file does not exist, a FileNotFoundError exception will be thrown.
Example
Section titled “Example”7. Rename a File or Directory
Section titled “7. Rename a File or Directory”The os.rename(src, dst) function is used to rename a file or directory. src is the original path, and dst is the new path.
Example
Section titled “Example”8. Get Environment Variables
Section titled “8. Get Environment Variables”The os.getenv(key) function is used to get the value of the specified environment variable. If the environment variable does not exist, None is returned.
Example
Section titled “Example”9. Execute System Commands
Section titled “9. Execute System Commands”The os.system(command) function is used to execute commands in the operating system’s shell. After the command is executed, the exit status of the command is returned.
Example
Section titled “Example”Common os Methods
Section titled “Common os Methods”The os module provides a very rich set of methods for handling files and directories. The commonly used methods are listed in the table below:
| No. | Method and Description |
|---|---|
| 1 |
Check permission mode |
| 2 |
Change the current working directory |
| 3 |
Set the flags of the path to numeric flags. |
| 4 |
Change permissions |
| 5 |
Change file owner |
| 6 |
Change the root directory of the current process |
| 7 |
Close file descriptor fd |
| 8 | os.closerange(fd_low, fd_high) Close all file descriptors from fd_low (inclusive) to fd_high (exclusive). Errors are ignored. |
| 9 |
Duplicate file descriptor fd |
| 10 |
Duplicate one file descriptor fd to another fd2 |
| 11 |
Change the current working directory via file descriptor |
| 12 |
Change the access permissions of a file specified by the fd parameter. The mode parameter is Unix file access permissions. |
| 13 |
Modify the ownership of a file. This function modifies the user ID and group ID of a file specified by the file descriptor fd. |
| 14 |
Force write the file to disk. The file is specified by the file descriptor fd, but does not force update the file's status information. |
| 15 | os.fdopen(fd[, mode[, bufsize]]) Create a file object via file descriptor fd and return this file object |
| 16 |
Return system configuration information for an open file. name is the system configuration value to retrieve, which may be a string defining system values as specified in many standards (POSIX.1, Unix 95, Unix 98, and others). |
| 17 |
Return the status of file descriptor fd, like stat(). |
| 18 |
Return information about the file system containing the file associated with file descriptor fd. Python 3.3 equivalent to statvfs(). |
| 19 |
Force write the file with file descriptor fd to the hard disk. |
| 20 |
Truncate the file corresponding to file descriptor fd so that it cannot exceed the file size. |
| 21 |
Return the current working directory |
| 22 |
Return a Unicode object of the current working directory |
| 23 |
Return true if the file descriptor fd is open and connected to a tty(-like) device, otherwise False. |
| 24 |
Set the flags of the path to numeric flags, similar to chflags(), but without following symbolic links |
| 25 |
Change the permissions of a linked file |
| 26 |
Change file owner, similar to chown, but does not follow links. |
| 27 |
Create a hard link named dst pointing to src |
| 28 |
Return a list of the names of files or folders contained in the folder specified by path. |
| 29 |
Set the current position of file descriptor fd to pos, modified by how: SEEK_SET or 0 sets pos from the beginning of the file; SEEK_CUR or 1 calculates from the current position; os.SEEK_END or 2 starts from the end of the file. Valid on Unix and Windows. |
| 30 |
Like stat(), but without following symbolic links |
| 31 |
Extract the device major number from a raw device number (using the st_dev or st_rdev field from stat). |
| 32 |
Compose a raw device number from major and minor device numbers |
| 33 |
Recursive directory creation function. Like mkdir(), but creates all intermediate-level directories needed to contain the subdirectory. |
| 34 |
Extract the device minor number from a raw device number (using the st_dev or st_rdev field from stat). |
| 35 |
Create a directory named path with numeric mode mode. The default mode is 0777 (octal). |
| 36 |
Create a named pipe. mode is numeric, defaulting to 0666 (octal) |
| 37 | os.mknod(filename[, mode=0600, device]) |
| 38 |
Open a file and set the required open options. The mode parameter is optional |
| 39 |
Open a new pseudo-terminal pair. Return file descriptors for pty and tty. |
| 40 |
Return system configuration information for the relevant file. |
| 41 |
Create a pipe. Return a pair of file descriptors (r, w) for reading and writing respectively |
| 42 | os.popen(command[, mode[, bufsize]]) Open a pipe from a command |
| 43 |
Read at most n bytes from file descriptor fd, returning a string containing the bytes read. If the file corresponding to fd has reached the end, return an empty string. |
| 44 |
Return the file pointed to by a symbolic link |
| 45 |
Delete the file at path path. If path is a folder, an OSError will be thrown; see rmdir() below to delete a directory. |
| 46 |
Recursively delete a directory. |
| 47 |
Rename a file or directory from src to dst |
| 48 |
Recursively rename a directory, or rename a file. |
| 49 |
Delete the empty directory specified by path. If the directory is not empty, an OSError exception is thrown. |
| 50 |
Get information about the path specified by path, functionally equivalent to the stat() system call in the C API. |
| 51 | os.stat_float_times([newvalue]) |
| 52 |
Get file system statistics for the specified path |
| 53 |
Create a symbolic link |
| 54 |
Return the process group associated with the terminal fd (an open file descriptor returned by os.open()) |
| 55 |
Set the process group associated with the terminal fd (an open file descriptor returned by os.open()) to pg. |
| 56 | os.tempnam([dir[, prefix]]) Removed in Python 3. Return a unique path name for creating a temporary file. |
| 57 | os.tmpfile() Removed in Python 3. Return an open file object in (w+b) mode. This file object has no directory entry, no file descriptor, and will be automatically deleted. |
| 58 | os.tmpnam() Removed in Python 3. Return a unique path for creating a temporary file |
| 59 |
Return a string representing the terminal device associated with file descriptor fd. If fd is not associated with a terminal device, an exception is raised. |
| 60 |
Delete the file path |
| 61 |
Return the access and modification times of the file specified by path. |
| 62 | os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]]) Output filenames in a folder by walking the tree, either up or down. |
| 63 |
Write a string to file descriptor fd. Returns the actual length of the string written |
| 64 |
Get file attribute information. |
| 65 |
Get the parent directory of the current directory, displayed as a string. |
| 66 |
Rename a file or directory. |
| 67 |
Used to open a file or folder on Windows. |