Table of Contents
os模块调用操作系统接口的模块                          
  相关方法或属性:
Home Backend Development Python Tutorial Detailed explanation of the use of python os module

Detailed explanation of the use of python os module

Aug 19, 2017 pm 02:48 PM
module Detailed explanation

os模块调用操作系统接口的模块                          

  相关方法或属性:

    getcwd() --- 获取当前的操作目录,等同于linux中的pwd命令。

      调用:os.getcwd()

    chdir() --- 改变python脚本的工作目录。

      调用:os.chdir(path) (path以字符串形式传入)

      例如:


>>> os.getcwd()'C:\\Users\\BLUE'>>> os.chdir('D:\\Program Files')>>> os.getcwd()'D:\\Program Files'>>> os.chdir(r'C:\Users\BLUE')>>> os.getcwd()'C:\\Users\\BLUE'
Copy after login


    curdir --- 当前目录   使用:os.curdir

    pardir --- 当前目录的父目录   使用: os.pardir

      例如:


>>> os.curdir'.'>>> os.pardir'..'>>> os.getcwd()'C:\\Users\\BLUE'>>> os.chdir(os.pardir)>>> os.getcwd()'C:\\Users'
Copy after login


    makedirs() --- 递归的创建目录。

      调用:os.makedirs('dir_1/dir_2/dir_3/.../dir_n')

      例如:os.makedirs(r'C:\a\b\c\d')  #该操作会依次在C盘下创建a, b, c, d四个文件夹(若a目录存在则只创建b,c,d三个目录)。

    removedirs() --- 若当前目录为空则删除,并切换到父级目录,若为空继续删除,依次递归。

      调用:os.removedirs('dir_1/dir_2/dir_3/.../dir_n')

      例如:os.removedirs(r'C:\a\b\c\d')  #该操作会依次在C盘下依次删除d, c, b, a四个文件夹,如果中间某一级目录不为空,则在该级停止删除。

    mkdir() --- 创建单级目录。

      调用:os.mkdir('dir_1/dir_2/dir_3/.../dir_n')

      例如:os.mkdir(r'C:\a\b\c\d')  #该操作会在C盘下创建d文件夹(若a, b, c目录有一个不存在,则无法创建并报错)。

    rmdir() --- 删除单级空目录。

      调用:os.rmdir('dir_1/dir_2/dir_3/.../dir_n')

      例如:os.rmdir(r'C:\a\b\c\d')  #若d目录为空,该操作只删除d目录, 否则无法删除并报错。

    listdir() --- 以列表的形式列出制定目录下的所有文件(包括隐藏文件),子目录。

      调用:os.listdir(path)

      例如:(列出D盘下的所有文件)


>>> os.listdir(r'D:')
['Anaconda3', 'BaiduNetdisk', 'BHO', 'Data', 'guiminer', 'Intel', 'JetBrains', 'Profiles', 'Program', 'Tencent', 'Thunder', 'Thunder BHO Platform', 'UninstallXLWFP.exe', 'WinRAR', '腾讯游戏']
Copy after login


    remove() --- 删除一个文件。

      调用:os.remove(path)

    rename() --- 对一个文件重命名。

      调用:os.rename(old_filename, new_filename)  #注意不能覆盖已存在文件

    stat() --- 获取文件或目录的属性信息。

      调用:os.stat(path)

      例如:


>>> os.stat(r'C:\Windows\regedit.exe')
os.stat_result(st_mode=33279, st_ino=281474976742063, st_dev=1893840342, st_nlink=2, st_uid=0, st_gid=0, st_size=321024, st_atime=1489870628, st_mtime=1489870628, st_ctime=1489870628)>>> os.stat(r'C:\Windows')
os.stat_result(st_mode=16895, st_ino=281474976712108, st_dev=1893840342, st_nlink=1, st_uid=0, st_gid=0, st_size=32768, st_atime=1502900732, st_mtime=1502900732, st_ctime=1489837220)
Copy after login


    sep --- 使用os.sep获取当前平台的路径的分隔符(目录与子目录之间)(例如windows下是r‘\’,Linux下时‘/’)。

    linesep --- 使用os.linesep获取当前平台的换行符(例如windows下是‘\r\n’,Linux下时‘\n’)。

    pathsep --- 使用os.pathsep获取当前平台文件路径的分隔符(文件之间)(例如windows下是‘;’,Linux下时‘:’)。

    name --- 使用os.name获取当前平台名称。

      例如:


>>> os.sep'\\'>>> os.linesep'\r\n'>>> os.pathsep';'>>> os.name'nt'
Copy after login


    system() --- 执行系统命令。

      调用:os.system(command)

      例如:


>>> os.system('ping www.baidu.com')

正在 Ping www.A.sHiFeN.com [220.181.112.244] 具有 32 字节的数据:
来自 220.181.112.244 的回复: 字节=32 时间=38ms TTL=55来自 220.181.112.244 的回复: 字节=32 时间=38ms TTL=55来自 220.181.112.244 的回复: 字节=32 时间=38ms TTL=55来自 220.181.112.244 的回复: 字节=32 时间=37ms TTL=55

220.181.112.244 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 37ms,最长 = 38ms,平均 = 37ms
Copy after login


    environ --- 使用os.environ获取系统环境变量。

      例如:


>>> os.environ
environ({'COMPUTERNAME': 'DESKTOP-KTUG9G5', 'APPDATA': 'C:\\Users\\BLUE\\AppData\\Roaming', 'USERDOMAIN_ROAMINGPROFILE': 'DESKTOP-KTUG9G5', 'HOMEPATH': '\\Users\\BLUE', 'NUMBER_OF_PROCESSORS': '8', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC', 'ONEDRIVE': 'C:\\Users\\BLUE\\OneDrive', 'LOGONSERVER': '\\\\DESKTOP-KTUG9G5', 'OS': 'Windows_NT', 'TEMP': 'C:\\Users\\BLUE\\AppData\\Local\\Temp', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'PROGRAMDATA': 'C:\\ProgramData', 'PROMPT': '$P$G', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 60 Stepping 3, GenuineIntel', 'LOCALAPPDATA': 'C:\\Users\\BLUE\\AppData\\Local', 'USERNAME': 'BLUE', 'PROCESSOR_REVISION': '3c03', 'PROGRAMFILES': 'C:\\Program Files', 'PROGRAMW6432': 'C:\\Program Files', 'WINDIR': 'C:\\Windows', 'PUBLIC': 'C:\\Users\\Public', 'ASL.LOG': 'Destination=file', 'PSMODULEPATH': 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules', 'PROCESSOR_LEVEL': '6', 'SYSTEMROOT': 'C:\\Windows', 'SESSIONNAME': 'Console', 'ALLUSERSPROFILE': 'C:\\ProgramData', 'SYSTEMDRIVE': 'C:', 'COMSPEC': 'C:\\Windows\\system32\\cmd.exe', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'HOMEDRIVE': 'C:', 'TMP': 'C:\\Users\\BLUE\\AppData\\Local\\Temp', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'PATH': 'D:\\Program Files\\Anaconda3\\Library\\bin;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;D:\\Program Files\\Anaconda3;D:\\Program Files\\Anaconda3\\Scripts;D:\\Program Files\\Anaconda3\\Library\\bin;C:\\Users\\BLUE\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\BLUE\\AppData\\Local\\GitHubDesktop\\bin', 'USERDOMAIN': 'DESKTOP-KTUG9G5', 'USERPROFILE': 'C:\\Users\\BLUE'})
Copy after login


    path.abspath() --- 获取文件的绝对路径

      调用:os.path.abspath(filename)

      例如:


>>> os.chdir(r'C:\windows')>>> os.path.abspath('regedit.exe')'C:\\windows\\regedit.exe'
Copy after login


    path.split() --- 传入一个文件路径,返回一个tuple(由两部分构成(path, filename))。

      调用:os.path.split(path)

      例如:

    path.dirname() --- 获取路径中的目录。

      调用:os.path.dirname(path)

    path.basename() --- 获取路径中的文件名。

      调用:os.path.basename(path)


>>> os.path.dirname(r'C:\Windows\System32\drivers\etc\hosts')'C:\\Windows\\System32\\drivers\\etc'>>> os.path.basename(r'C:\Windows\System32\drivers\etc\hosts')'hosts'>>> os.path.split(r'C:\Windows\System32\drivers\etc\hosts')
('C:\\Windows\\System32\\drivers\\etc', 'hosts')
Copy after login


    path.exists() --- 判断路径是否存在。

      调用:os.path.exists(path)

    path.isabs() --- 判断路径是否是绝对路径。

      调用:os.path.isabs(path)

    path.isfile() --- 判断是否是文件。

      调用:os.path.isfile(path)

    path.isdir() --- 判断是否是目录。

      调用:os.path.isdir(path)

      例如:


>>> os.path.exists(r'C:\Windows\System32\drivers\etc\hosts')
True>>> os.path.exists(r'C:\Windows\System32\drivers\etc\abcd')
False>>> os.path.isabs(r'C:\Windows\System32\drivers\etc\hosts')
True>>> os.path.isabs(r'../')
False>>> os.path.isfile('C:\Windows\System32\drivers\etc\hosts')
True>>> os.path.isfile('C:\Windows\System32\drivers\etc')
False>>> os.path.isdir('C:\Windows\System32\drivers\etc')
True>>> os.path.isdir('C:\Windows\System32\drivers\etc\hosts')
False
Copy after login


    path.join() --- 将一个或多个路径正确地连接起来。

      调用:os.path.join(path, *paths)

    path.getatime() --- 获取文件最后的访问时间(以时间戳的形式返回)。

      调用:os.path.getatime(path)

    path.getmtime() --- 获取文件最后的修改时间(以时间戳的形式返回)。

      调用:os.path.getmtime(path)

      例如:


>>> os.path.join('C:', r'\windows\System32', r'\System32\drivers')'C:\\System32\\drivers'>>> os.path.join('C:', r'\windows\System32')'C:\\windows\\System32'>>> os.path.getatime('C:\Windows\System32\drivers\etc\hosts')1501070798.585747
>>> os.path.getmtime('C:\Windows\System32\drivers\etc\hosts')1502505489.0068946
Copy after login


 

The above is the detailed content of Detailed explanation of the use of python os module. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

WLAN expansion module has stopped [fix] WLAN expansion module has stopped [fix] Feb 19, 2024 pm 02:18 PM

If there is a problem with the WLAN expansion module on your Windows computer, it may cause you to be disconnected from the Internet. This situation is often frustrating, but fortunately, this article provides some simple suggestions that can help you solve this problem and get your wireless connection working properly again. Fix WLAN Extensibility Module Has Stopped If the WLAN Extensibility Module has stopped working on your Windows computer, follow these suggestions to fix it: Run the Network and Internet Troubleshooter to disable and re-enable wireless network connections Restart the WLAN Autoconfiguration Service Modify Power Options Modify Advanced Power Settings Reinstall Network Adapter Driver Run Some Network Commands Now, let’s look at it in detail

WLAN extensibility module cannot start WLAN extensibility module cannot start Feb 19, 2024 pm 05:09 PM

This article details methods to resolve event ID10000, which indicates that the Wireless LAN expansion module cannot start. This error may appear in the event log of Windows 11/10 PC. The WLAN extensibility module is a component of Windows that allows independent hardware vendors (IHVs) and independent software vendors (ISVs) to provide users with customized wireless network features and functionality. It extends the capabilities of native Windows network components by adding Windows default functionality. The WLAN extensibility module is started as part of initialization when the operating system loads network components. If the Wireless LAN Expansion Module encounters a problem and cannot start, you may see an error message in the event viewer log.

Detailed explanation of the mode function in C++ Detailed explanation of the mode function in C++ Nov 18, 2023 pm 03:08 PM

Detailed explanation of the mode function in C++ In statistics, the mode refers to the value that appears most frequently in a set of data. In C++ language, we can find the mode in any set of data by writing a mode function. The mode function can be implemented in many different ways, two of the commonly used methods will be introduced in detail below. The first method is to use a hash table to count the number of occurrences of each number. First, we need to define a hash table with each number as the key and the number of occurrences as the value. Then, for a given data set, we run

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of remainder function in C++ Detailed explanation of remainder function in C++ Nov 18, 2023 pm 02:41 PM

Detailed explanation of the remainder function in C++ In C++, the remainder operator (%) is used to calculate the remainder of the division of two numbers. It is a binary operator whose operands can be any integer type (including char, short, int, long, etc.) or a floating-point number type (such as float, double). The remainder operator returns a result with the same sign as the dividend. For example, for the remainder operation of integers, we can use the following code to implement: inta=10;intb=3;

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

See all articles