Python3 OS File/Directory Methods

osThe module is an important module in the Python standard library, providing functions for interacting with the operating system.

Throughosthe module, you can perform tasks such as file operations, directory operations, environment variable management, and process management.

osThe module is cross-platform, which means you can use the same code on different operating systems (such as Windows, Linux, macOS).

Before usingosthe module, you need to import it first. ImportosThe code for the module is as follows:

import os

Common functions of the os module

1. Get the current working directory

os.getcwd()The function is used to get the path of the current working directory. The current working directory is the directory where the Python script is executed.

Example

current_directory = os.getcwd()
print("Current working directory:", current_directory)

2. Change the current working directory

os.chdir(path)The function is used to change the current working directory.pathis the path to the directory you want to switch to.

Example

os.chdir("/path/to/new/directory")
print("New working directory:", os.getcwd())

3. List directory contents

os.listdir(path)The function is used to list all files and subdirectories in the specified directory. If not providedpathparameter, it lists the contents of the current working directory by default.

Example

files_and_dirs = os.listdir()
print("Directory contents:", files_and_dirs)

4. Create a directory

os.mkdir(path)The function is used to create a new directory. If the directory already exists, it will raiseFileExistsErroran exception.

Example

os.mkdir("new_directory")

5. Delete a directory

os.rmdir(path)The function is used to delete an empty directory. If the directory is not empty, it will raiseOSErroran exception.

Example

os.rmdir("new_directory")

6. Delete a file

os.remove(path)The function is used to delete a file. If the file does not exist, it will raiseFileNotFoundErroran exception.

Example

os.remove("file_to_delete.txt")

7. Rename a file or directory

os.rename(src, dst)The function is used to rename a file or directory.srcis the original path,dstis the new path.

Example

os.rename("old_name.txt", "new_name.txt")

8. Get an environment variable

os.getenv(key)The function is used to get the value of the specified environment variable. If the environment variable does not exist, it returnsNone。

Example

home_directory = os.getenv("HOME")
print("HOME directory:", home_directory)

9. Execute system commands

os.system(command)The function is used to execute commands in the operating system shell. After the command is executed, it returns the exit status of the command.

Example

os.system("ls -l")

Common methods of os

osThe 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

os.access(path, mode)


Check permission mode
2

os.chdir(path)


Change the current working directory
3

os.chflags(path, flags)


Set the flags of the path to numeric flags.
4

os.chmod(path, mode)


Change permissions
5

os.chown(path, uid, gid)


Change file owner
6

os.chroot(path)


Change the root directory of the current process
7

os.close(fd)


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

os.dup(fd)


Copy file descriptor fd
10

os.dup2(fd, fd2)


Copy a file descriptor fd to another fd2
11

os.fchdir(fd)


Change the current working directory through a file descriptor
12

os.fchmod(fd, mode)


Change the access permissions of a file specified by the parameter fd. The parameter mode is the file access permission under Unix.
13

os.fchown(fd, uid, gid)


Modify the ownership of a file. This function modifies the user ID and user group ID of a file, which is specified by the file descriptor fd.
14

os.fdatasync(fd)


Force the file to be written to disk, specified by file descriptor fd, but does not force the file status information to be updated.
15

os.fdopen(fd[, mode[, bufsize]])


Create a file object from file descriptor fd, and return this file object
16

os.fpathconf(fd, name)


Return the system configuration information of an open file. name is the value of the system configuration to retrieve. It may be a string that defines a system value. These names are specified in many standards (POSIX.1, Unix 95, Unix 98, and others).
17

os.fstat(fd)


Return the status of file descriptor fd, like stat().
18

os.fstatvfs(fd)


Return the file system information of the file containing file descriptor fd. In Python 3.3, it is equivalent to statvfs().
19

os.fsync(fd)


Force the file with file descriptor fd to be written to the hard disk.
20

os.ftruncate(fd, length)


Truncate the file corresponding to file descriptor fd, so that it cannot exceed the file size.
21

os.getcwd()


Return the current working directory
22

os.getcwdb()


Return a Unicode object of the current working directory
23

os.isatty(fd)


If file descriptor fd is open and connected to a tty(-like) device, return true, otherwise False.
24

os.lchflags(path, flags)


Set the flags of the path to numeric flags, similar to chflags(), but without symbolic links
25

os.lchmod(path, mode)


Modify link file permissions
26

os.lchown(path, uid, gid)


Change file owner, similar to chown, but does not follow links.
27

os.link(src, dst)


Create a hard link named parameter dst, pointing to parameter src
28

os.listdir(path)


Return a list of names of files or folders contained in the folder specified by path.
29

os.lseek(fd, pos, how)


Set the current position of file descriptor fd to pos. The how method modifies: SEEK_SET or 0 sets pos calculated 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 in Unix and Windows.
30

os.lstat(path)


Like stat(), but without symbolic links
31

os.major(device)


Extract the device major number from the raw device number (using the st_dev or st_rdev field in stat).
32

os.makedev(major, minor)


Compose a raw device number from the major and minor device numbers.
33

os.makedirs(path[, mode])


Recursive folder creation function. Like mkdir(), but creates all intermediate-level folders required to contain subfolders.
34

os.minor(device)


Extract the device minor number from the raw device number (using the st_dev or st_rdev field in stat).
35

os.mkdir(path[, mode])


Create a folder named path with a numeric mode. The default mode is 0777 (octal).
36

os.mkfifo(path[, mode])


Create a named pipe. mode is numeric, default is 0666 (octal)
37

os.mknod(filename[, mode=0600, device])
Create a file system node named filename (file, device special file, or named pipe).

38

os.open(file, flags[, mode])


Open a file and set the required opening options. The mode parameter is optional.
39

os.openpty()


Open a new pseudo-terminal pair. Return the file descriptors of pty and tty.
40

os.pathconf(path, name)


Return the system configuration information of the related file.
41

os.pipe()


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

os.read(fd, n)


Read at most n bytes from file descriptor fd, return a string containing the bytes read. If the file corresponding to file descriptor fd has reached the end, return an empty string.
44

os.readlink(path)


Return the file pointed to by the symbolic link
45

os.remove(path)


Delete the file whose path is path. If path is a folder, OSError will be raised; see rmdir() below to delete a directory.
46

os.removedirs(path)


Recursively delete directories.
47

os.rename(src, dst)


Rename a file or directory, from src to dst
48

os.renames(old, new)


Recursively rename directories, and can also rename files.
49

os.rmdir(path)


Delete the empty directory specified by path. If the directory is not empty, an OSError exception is raised.
50

os.stat(path)


Get the information of the path specified by path. Its function is 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.

52

os.statvfs(path)


Get the file system statistics information of the specified path.
53

os.symlink(src, dst)


Create a symbolic link
54

os.tcgetpgrp(fd)


Return the process group associated with the terminal fd (an open file descriptor returned by os.open()).
55

os.tcsetpgrp(fd, pg)


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 Python3.Return a unique path name for creating a temporary file.
57

os.tmpfile()


Removed in Python3.Returns a file object opened in (w+b) mode. This file object has no directory entry, no file descriptor, and will be automatically deleted.
58

os.tmpnam()


Removed in Python3.Returns a unique path for creating a temporary file.
59

os.ttyname(fd)


Returns 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

os.unlink(path)


Delete the file path.
61

os.utime(path, times)


Returns the access and modification times of the file at the specified path.
62

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])


Outputs file names in a directory by walking the tree, up or down.
63

os.write(fd, str)


Writes a string to file descriptor fd. Returns the actual length of the string written.
64

os.path module.


Get file attribute information.
65

os.pardir()


Get the parent directory of the current directory, displaying the directory name as a string.
66

os.replace()


Rename a file or directory.
67

os.startfile()


Used to open a file or folder on Windows.
Other extensions.