Home Backend Development Python Tutorial How to use Python's OS module and examples

How to use Python's OS module and examples

Apr 22, 2023 pm 10:19 PM
python module os

Python's os module is one of the standard libraries used to interact with the operating system. It provides many useful functions and variables for working with files and directories. The following are the usage of some common os module functions:

1. Get the current working directory:

1

2

3

import os

cwd = os.getcwd()

print(cwd)

Copy after login

2. Switch the current working directory:

1

2

import os

os.chdir('/path/to/new/directory')

Copy after login

3. List the directory All files and subdirectories in:

1

2

3

import os

files = os.listdir('/path/to/directory')

print(files)

Copy after login

4. Check whether the given path is a directory:

1

2

3

4

5

6

import os

path = '/path/to/directory'

if os.path.isdir(path):

    print("It's a directory")

else:

    print("It's not a directory")

Copy after login

5. Check whether the given path is a file:

1

2

3

4

5

6

import os

path = '/path/to/file'

if os.path.isfile(path):

    print("It's a file")

else:

    print("It's not a file")

Copy after login

6. Get the size of the file in bytes:

1

2

3

4

import os

path = '/path/to/file'

size = os.path.getsize(path)

print(size)

Copy after login

7. Check if the given path exists:

1

2

3

4

5

6

import os

path = '/path/to/file_or_directory'

if os.path.exists(path):

    print("It exists")

else:

    print("It doesn't exist")

Copy after login

8. Create a new directory:

1

2

3

import os

path = '/path/to/new/directory'

os.mkdir(path)

Copy after login

9. Recursively create new directories (if the directory does not exist):

1

2

3

import os

path = '/path/to/new/directory'

os.makedirs(path, exist_ok=True)

Copy after login

10. Delete files or empty directories:

1

2

3

import os

path = '/path/to/file_or_directory'

os.remove(path)

Copy after login

11. Recursively delete directories and their contents:

1

2

3

import os

path = '/path/to/directory'

os.system('rm -rf ' + path)

Copy after login

Some other convenient uses:

12.os.path.splitext() method is to split a path into two parts: file name and extension. It uses the last "." in the file name as a delimiter to separate the file name and extension. For example, if the file path is "/path/to/file.txt", the os.path.splitext() method returns a tuple ("/path/to/file", ".txt").

It should be noted that if there is no "." in the file name, the returned extension is an empty string. If the file name begins with ".", it is considered a file without extension and the os.path.splitext() method will return (file path, '').

The following is an example:

1

2

3

4

5

import os

path = '/path/to/file.txt'

file_name, ext = os.path.splitext(path)

print('文件名为:', file_name)

print('扩展名为:', ext)

Copy after login

The output result is:

The file name is: /path/to/file
The extension is: .txt

13. Set file permissions:

1

2

import os

os.chmod('/path/to/file', 0o777) # 设置读、写、执行权限

Copy after login

os.chmod() method can be used to modify the access permissions of files or directories. It accepts two parameters: file path and new permission mode. Permission mode can be represented by an octal number, with each bit representing a different permission.

Here are some examples of permission modes:

  • 0o400: Read-only permission

  • 0o200: Write permission

  • 0o100: Execution permission

  • 0o700: All permissions

14. Get the number of CPUs:

1

2

3

import os

cpu_count = os.cpu_count()

print('CPU数量为:', cpu_count)

Copy after login

It should be noted that the number of CPUs returned by os.cpu_count() is the number of physical CPU cores and does not include the virtual cores of hyper-threading technology. In systems with Hyper-Threading Technology, each physical CPU core is divided into two virtual cores, so the os.cpu_count() method may return a number greater than the actual number of CPU cores.

In addition, the os.cpu_count() method may have different implementations on different operating systems. On some operating systems, it may only return the number of logical CPU cores, not the number of physical CPU cores. Therefore, when using this method, it is best to consult the relevant documentation for more information.

15. Start a new process:

1

2

import os

os.system('notepad.exe')

Copy after login

The os.system() method can execute a command on the operating system and return the command's exit status code. Its parameter is a string type command, which can be any valid system command.

The following is an example that demonstrates how to use the os.system() method to execute a simple command:

1

2

import os

os.system('echo "Hello, World!"')

Copy after login

The above code will output the Hello, World! string and return the command's Exit status code (usually 0 for success).

It should be noted that the os.system() method will block the current process until the command execution is completed. If you want to execute the command without blocking the current process, you can consider using other methods in the subprocess module, such as subprocess.Popen().

The following is another example that demonstrates how to use the os.system() method to execute a complex command, such as using wget to download a file on a Linux system:

1

2

3

4

5

import os

url = 'https://example.com/file.zip'

output_dir = '/path/to/output'

command = f'wget {url} -P {output_dir}'

os.system(command)

Copy after login

The above code will Download the file specified by the url parameter to the directory specified by the output_dir parameter, and return the command's exit status code.

16.os.environ: This is a dictionary containing the current environment variables. You can use os.environ[key] to get the value of a specific environment variable.

17.os.exec*(): These methods allow Python programs to execute other programs in the current process, replacing the current process. For example, the os.execv() method can execute a program using a specified argument list, replacing the current process.

18.os.fork(): This method can create a child process on the Unix or Linux operating system for parallel execution of the program. The child process will copy all the memory contents of the parent process, including code, data, stack, etc., so the program can continue to execute based on the parent process.

19.os.kill(): This method is used to send a signal to the specified process. You can use the os.kill(pid, signal) method to send a specified signal to a specified process. Commonly used signals include SIGINT (interrupt signal), SIGTERM (termination signal) and SIGKILL (forced termination signal), etc.

20.os.pipe(): This method can create a pipe for communication between processes. The os.pipe() method will return two file descriptors, one for reading pipe data and the other for writing pipe data.

21.os.wait(): This method can wait for the end of the child process and then return the status code of the child process. You can use the os.waitpid(pid, options) method to wait for the specified process to end and return the status code of the process.

22.os模块可以用来操作文件路径。例如,os.path.join(path, *paths)可以将多个路径拼接成一个完整路径,os.path.abspath(path)可以将相对路径转换为绝对路径,os.path.split(path)可以将路径分割成目录和文件名。

23.遍历目录树

1

2

3

4

5

6

import os

def list_files(path):

    for root, dirs, files inos.walk(path):

        for file in files:

            print(os.path.join(root, file))

list_files('.')

Copy after login

这段代码可以遍历当前工作目录及其子目录下的所有文件,并打印出它们的完整路径。

os.walk()是os模块中一个非常有用的函数,用于遍历指定目录及其子目录下的所有文件和目录。它返回一个三元组(root, dirs, files),其中root是当前目录的路径,dirs是当前目录下的子目录列表,files是当前目录下的文件列表。下面是一个os.walk()的详细解释和示例:

1

2

for root, dirs, files in os.walk(top, topdown=True, onerror=None, followlinks=False):

    # Do something with root, dirs, and files

Copy after login

top是指定的目录路径,可以是相对路径或绝对路径。

  • topdown是一个布尔值,表示遍历时是否先遍历当前目录,再遍历子目录。如果为True(默认值),则先遍历当前目录,再遍历子目录;如果为False,则先遍历子目录,再遍历当前目录。

  • onerror是一个可选的错误处理函数,如果在遍历过程中出现错误,则会调用这个函数。

  • followlinks是一个布尔值,表示是否跟随符号链接。如果为True,则会跟随符号链接遍历目录;如果为False(默认值),则会忽略符号链接。

在遍历过程中,os.walk()会依次遍历指定目录及其子目录下的所有文件和目录,并返回当前目录的路径、子目录列表和文件列表。可以通过遍历返回的三元组来处理目录和文件。例如,可以使用下面的代码列出指定目录下的所有文件和子目录:

1

2

3

4

5

6

7

8

9

10

11

import os

  

def list_files_and_dirs(path):

    for root, dirs, files in os.walk(path):

        print(f'Directory: {root}')

        for file in files:

            print(f'  File: {os.path.join(root, file)}')

        for dir in dirs:

            print(f'  Subdirectory: {os.path.join(root, dir)}')

  

list_files_and_dirs('.')

Copy after login

这段代码会遍历当前工作目录及其子目录下的所有文件和目录,并输出相应的信息。

需要注意的是,os.walk()只会遍历当前目录及其子目录下的文件和目录,不会遍历符号链接所指向的文件或目录。如果需要遍历符号链接所指向的文件或目录,需要设置followlinks=True。

The above is the detailed content of How to use Python's OS module and examples. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1676
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles