Python3 OS File/Directory Methods
os is an important module in the Python standard library that provides functions for interacting with the operating system.
Pass os module, you can perform file operations, directory operations, environment variable management, process management and other tasks.
os The module is cross-platform, which means you can use the same code on different operating systems (such as Windows, Linux and macOS).
When using os module, you need to import it first. Import the os module with the following code:
import os
Common functions of the os module
1. Get the current working directory
os.getcwd() function gets the path of the current working directory. The current working directory is the directory in which the Python script is executed.
Example
current_directory
=
os
.
getcwd
(
)
(
"Current working directory:"
,
current_directory
)
2. Change the current working directory
os.chdir(path) function changes the current working directory.path is the path of the directory you want to switch to.
Example
os
.
chdir
(
"/path/to/new/directory"
)
(
"New working directory:"
,
os
.
getcwd
(
)
)
3. List directory contents
os.listdir(path) function lists all files and subdirectories in the specified directory. If the path parameter is not given, it lists the contents of the current working directory by default.
Example
files_and_dirs
=
os
.
listdir
(
)
(
"Directory contents:"
,
files_and_dirs
)
4. Create a directory
os.mkdir(path) function creates a new directory. If the directory already exists, it raises FileExistsError exception.
Example
os
.
mkdir
(
"new_directory"
)
5. Delete a directory
os.rmdir(path) function deletes an empty directory. If the directory is not empty, it raises OSError exception.
Example
os
.
rmdir
(
"new_directory"
)
6. Delete a file
os.remove(path) function deletes a file. If the file does not exist, it raises FileNotFoundError exception.
Example
os
.
remove
(
"file_to_delete.txt"
)
7. Rename a file or directory
os.rename(src, dst) function renames a file or directory.src is the original path,dst is the new path.
Example
os
.
rename
(
"old_name.txt"
,
"new_name.txt"
)
8. Get environment variables
os.getenv(key) function gets the value of a specified environment variable. If the variable does not exist, it returns None。
Example
home_directory
=
os
.
getenv
(
"HOME"
)
(
"HOME directory:"
,
home_directory
)
9. Execute system commands
os.system(command) function executes a command in the operating system's shell. After the command runs, it returns the command's exit status.
Example
os
.
system
(
"ls -l"
)
Common os methods
os module provides a very rich set of methods for handling files and directories. The commonly used methods are shown in the following table:
| No. | Method and description |
|---|---|
| 1 | |
| Check the permission mode | |
| 2 | |
| Change the current working directory | |
| 3 | |
| Set the flags of a path to numeric flags. | |
| 4 | |
| Change permissions | |
| 5 | |
| Change the file owner | |
| 6 | |
| Change the root directory of the current process | |
| 7 | |
| Close the file descriptor fd | |
| 8 | |
| Close all file descriptors from fd_low (inclusive) to fd_high (exclusive); errors are ignored | |
| 9 | |
| Duplicate the file descriptor fd | |
| 10 | |
| Duplicate one file descriptor fd onto another fd2 | |
| 11 | |
| Change the current working directory through a file descriptor | |
| 12 | |
| Change the access permissions of a file specified by the parameter fd; the parameter mode is the Unix file access permission. | |
| 13 | |
| Change the ownership of a file; this function changes the user ID and group ID of the file specified by the file descriptor fd. | |
| 14 | |
| Force a file specified by the file descriptor fd to be written to disk, but do not force the file's status information to be updated. | |
| 15 | |
| Create a file object from a file descriptor fd and return that file object | |
| 16 | |
| Return system configuration information for an open file. name is the system configuration value to retrieve; it may be a string defining a system value, and these names are specified in many standards (POSIX.1, Unix 95, Unix 98 and others). | |
| 17 | |
| Return the status of the file descriptor fd, like stat(). | |
| 18 | |
| Return information about the file system of the file containing the file descriptor fd; equivalent to statvfs() in Python 3.3. | |
| 19 | |
| Force the file with file descriptor fd to be written to disk. | |
| 20 | |
| Truncate the file corresponding to the 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 a path to numeric flags, similar to chflags(), but without following symbolic links | |
| 25 | |
| Change the permissions of a linked file | |
| 26 | |
| Change the file owner, similar to chown, but without following links. | |
| 27 | |
| Create a hard link named by the parameter dst pointing to the parameter src | |
| 28 | |
| Return a list of the names of files or folders contained in the directory specified by path. | |
| 29 | |
| Set the current position of the file descriptor fd to pos, with how specifying the method: SEEK_SET or 0 sets pos relative to the start 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 in stat). | |
| 32 | |
| Compose a raw device number from the major and minor device numbers | |
| 33 | |
| Recursive directory creation function. Like mkdir(), but all intermediate-level directories created need to contain subdirectories. | |
| 34 | |
| Extract the device minor number from a raw device number (using the st_dev or st_rdev field in stat). | |
| 35 | |
| Create a directory named path with the numeric mode mode. The default mode is 0777 (octal). | |
| 36 | |
| Create a named pipe with a numeric mode, defaulting to 0666 (octal) | |
| 37 |
Create a file system node named filename (a file, device special file or named pipe). | | 38 | Open a file and set the required opening options; the mode parameter is optional | | 39 | Open a new pseudo-terminal pair. Returns the file descriptors of the pty and tty. | | 40 | Return system configuration information for the related file. | | 41 | Create a pipe. Returns 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 the file descriptor fd and return a string containing the bytes read; if the file corresponding to fd has reached its end, return an empty string. | | 44 | Return the file pointed to by a symbolic link | | 45 | Delete the file at path. If path is a directory, OSError is raised; see rmdir() below for deleting a directory. | | 46 | Recursively delete directories. | | 47 | Rename a file or directory from src to dst | | 48 | Recursively rename directories, and can also rename files. | | 49 | Delete the empty directory specified by path; if the directory is not empty, raise an OSError exception. | | 50 | Get information about the path specified by path, equivalent to the stat() system call in the C API. | | 51 |os.stat_float_times([newvalue])
Determine whether stat_result displays timestamps as float objects
os.tempnam([dir[, prefix]])
**Removed in Python3.** Return a unique path name for creating a temporary file. | | 57 |os.tmpfile()
**Removed in Python3.** Return a file object opened in mode (w+b). This file object has no directory entry and no file descriptor, and will be deleted automatically. | | 58 |os.tmpnam()
**Removed in Python3.** Return a unique path for creating a temporary file | | 59 | Return a string representing the terminal device associated with the file descriptor fd. If fd is not associated with a terminal device, raise an exception. | | 60 | Delete a 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 the file names in a directory by walking the tree upwards or downwards. | | 63 | Write a string to the file descriptor fd. Return the actual number of characters written | | 64 | Get the attribute information of a file. | | 65 | Get the parent directory of the current directory, showing the directory name as a string. | | 66 | Rename a file or directory. | | 67 | Used to open a file or folder on Windows. |