博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python中os函数_Python os库函数
阅读量:2533 次
发布时间:2019-05-11

本文共 10409 字,大约阅读时间需要 34 分钟。

python中os函数

Python OS module allows us to use the operating system dependent functionalities and to interact with the underlying operating system in several different ways. For example, we can work with files, change the environment variables, and we can move files around, etc. This is as same as overriding all the os built-in functionalities in a module and using them in a file I/O and system handling.

Python OS模块允许我们使用依赖于操作系统的功能,并以几种不同的方式与基础操作系统进行交互。 例如,我们可以处理文件,更改环境变量,可以移动文件等。这与覆盖模块中的所有os内置功能以及在文件I / O和系统中使用它们相同。处理。

Python导入操作系统 (Python import os)

Now, as it is a built-in module, so we don’t have to install any third-party libraries. We can import the os module in our program like this:

现在,由于它是一个内置模块,因此我们不必安装任何第三方库。 我们可以像这样将os模块导入程序中:

import os  # importing the complete os modulefrom os import name  # importing a variable from the os module

Let’s look at a simple example of using the os module.

让我们看一个使用os模块的简单示例。

Code:

码:

import osprint(dir(os))

Output:

输出:

Python Os Module

Python Os Module

Python Os模块

NOTE: By printing this built-in dir() function and pass the os module, it shows us all of the attributes and methods that we have access to within this module.

注意:通过打印此内置dir()函数并传递os模块,它向我们显示了我们可以在此模块中访问的所有属性和方法。

OS模块的常用功能 (OS Module Common Functions)

OS module provides some callable methods and some variables. Some of the common methods for different functional categories are:

OS模块提供了一些可调用的方法和一些变量。 用于不同功能类别的一些常用方法是:

  1. Manipulating directories:

    操作目录:
  • chdir()

    chdir()
  • getcwd()

    getcwd()
  • listdir()

    listdir()
  • mkdir()

    mkdir()
  • makedirs()

    makedirs()
  • rmdir()

    rmdir()
  • removedirs()

    removeirs()
  1. Removing a file:

    删除文件:
  • remove()

    去掉()
  1. Renaming files/directories:

    重命名文件/目录:
  • rename()

    改名()
  1. Using more than one process:

    使用多个过程
  • system()

    系统()
  • popen()

    popen()
  • close()

    关()
  • walk()

    步行()
  1. User id and process id:

    用户标识和进程标识:
  • getgid(), os.getuid(), os.getpid()

    getgid(),os.getuid(),os.getpid()
  1. More about directories and files:

    有关目录和文件的更多信息:
  • error

    错误
  • stat()

    stat()
  1. Cross-plateform os attributes:

    跨平台os属性:
  • name

    名称
  1. Accessing environment variables:

    访问环境变量:
  • environ

    环境

常用功能说明和用法 (Common Functions Explanation and Usage)

  1. os.name: This is the name of the imported operating system dependent module. Some of the registered module are – ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’ and ‘riscos’.

    os.name:这是导入的操作系统相关模块的名称。 一些已注册的模块是–'posix','nt','os2','ce','java'和'riscos'。
print(os.name)

Output:

输出:

Os Name

Os Name

操作系统名称

  1. os.error: It is environment error class for I/O errors and OSError and is raised when any function returns any system-related error. Each of the or module functions returns these errors when any invalid or inaccessible file is triggered in the line-of-code.

    os.error:这是I / O错误和OSError的环境错误类,当任何函数返回任何与系统相关的错误时引发。 当在代码行中触发任何无效或不可访问的文件时,每个或模块函数都会返回这些错误。
import ostry:    filename = 'abcd2.txt'    f = open(filename, 'r')    text = f.read()    f.close()except os.error:    print('Problem reading: ' + filename)

Output:

输出:

Os Error

Os Error

操作系统错误

  1. os.system(): executing a shell command.

    os.system():执行一个shell命令。
cmd = "git --version"returned_value = os.system(cmd)  # returns the exit code in unixprint('returned value:', returned_value)

­

OUTPUT:

输出:

Linux os.system example

Linux os.system example

Linux操作系统示例

  1. os.environ(): It is known as the value of an object which returns all the directories of all user environment variables .E.g. ‘HOME’-directory environment variables

    os.environ():这是一个对象的值,该对象返回所有用户环境变量的所有目录。例如'HOME'-目录环境变量
import osos.chdir('C:/Users/user/Desktop/temp')# returns all the environment variablesprint(os.environ)# to get in particularprint(os.environ.get('TEMP'))

OUTPUT:

输出:

Linux os.environ Example

Linux os.environ Example

Linux os.environ示例

  1. os.getcwd(): returns the current working directory(CWD) in which the user is currently.

    os.getcwd():返回用户当前所在的当前工作目录(CWD)。
print(os.getcwd())

OUTPUT:  C:\Users\user\.PyCharmCE2017.3\config\scratches

输出: C:\Users\user\.PyCharmCE2017.3\config\scratches

  1. os.chdir(): to change the directory.

    os.chdir():更改目录。
os.chdir('C:/Users/user/.PyCharmCE2017.3/')print(os.getcwd())

OUTPUT:  C:\Users\user\.PyCharmCE2017.3

输出: C:\Users\user\.PyCharmCE2017.3

  1. os.listdir(): It returns a list of files and the folders in the current directory.

    os.listdir():返回当前目录中文件和文件夹的列表。
print(os.listdir())

OUTPUT: ['.git', '1802.04103.pdf', '1st year', '2K16-CO-200', 'abc.txt', 'afcat',]

输出['.git', '1802.04103.pdf', '1st year', '2K16-CO-200', 'abc.txt', 'afcat',]

  1. os.popen(command[, mode[, bufsize]]) : it opens a pipe to or from command. It returns an open file object connected to the pipe, which can be read or written depending on whether the mode is ‘r’ (default) or ‘w’.

    os.popen(command [,mode [,bufsize]]) :它打开到命令的管道。 它返回连接到管道的打开文件对象,可以根据模式是“ r”(默认)还是“ w”来对其进行读取或写入。
import osfd = "abc.txt"# popen() is similar to open()file = open(fd, 'w')file.write("Hello")file.close()file = open(fd, 'r')text = file.read()print(text)# popen()and accesses the file directlyfile = os.popen(fd, 'w')file.write("Hello")

OUTPUT:

输出:

Os Popen

Os Popen

奥斯普彭

Os Popen Notepad

Os Popen Notepad

Os Popen记事本

  1. os.close(): Close file descriptor fd.

    os.close():关闭文件描述符fd。

Note: It must be applied to a file descriptor returned by os.open() or pipe() built-in functions of os module.

注意:必须将其应用于os模块的os.open()或pipe()内置函数返回的文件描述符。

fd = "abc.txt"file = open(fd, 'r')text = file.read()print(text)os.close(file)

OUTPUT:

输出:

Os Close

Os Close

关闭

NOTE: Error is thrown for the non-existence of the file or the permission privileges.

注意 :由于文件不存在或权限特权而引发错误。

  1. os.getgid(), os.getuid(), os.getpid(), and os.stat(): getgid() returns the real group id for the current process. The getuid() function returns the current process’s user id and getpid() returns real process id of the current process. The os.stat() function returns the list of details about the file or the directory name given in the argument.

    os.getgid(),os.getuid(),os.getpid()和os.stat(): getgid()返回当前进程的真实组ID。 getuid()函数返回当前进程的用户ID,而getpid()返回当前进程的真实进程ID。 os.stat()函数返回有关文件或参数中给出的目录名称的详细信息列表。
print(os.stat('abcd1'))# for some simplified and particular details# we can use dot operator and that attribute name# this returns the timestamp of last modification timeprint(os.stat('abcd1').st_mtime)# this returns the size of the file in bytesprint(os.stat('abcd1').st_size)

OUTPUT:

输出:

Linux os.stat Example

Linux os.stat Example

Linux os.stat示例

  1. os.walk(): it is a generator that yields a couple of three values as it is walking the directory tree and for each directory that it traverses and produces the directory path, the direct within that path and the files within that path. It is useful to keep track of all the directories.

    os.walk():它是一个生成器,它在遍历目录树时会产生两个三个值,并且会为它遍历的每个目录生成目录路径,该路径内的直接路径以及该路径内的文件。 跟踪所有目录很有用。
os.chdir('C:/Users/user/Desktop/temp')# returns a 3-tuplefor dirpath, dirname, filename in os.walk('C:/Users/user/Desktop/temp'):    print('Current path: ',dirpath)    print('Directories: ', dirname)    print('Files: ', filename)    print()

OUTPUT:

输出:

Os Walk

Os Walk

奥斯沃克

  1. os.mkdir() and os.makedirs(): To create new directories.

    os.mkdir()和os.makedirs():创建新目录。

Differences: makedirs() creates all the intermediate directories if they don’t exist already and mkdir() can create a single sub-directory and will throw an exception if intermediate directories that don’t exist are specified.

区别 :makedirs()创建所有中间目录(如果尚不存在),而mkdir()可以创建单个子目录,并且如果指定了不存在的中间目录,则将引发异常。

OUTPUT:

输出:

['.git', '1802.04103.pdf', '1st year', '2K16-CO-200', 'abc.txt', 'abcd', 'abcd1', 'afcat',]Traceback (most recent call last):File "C:/Users/user/.PyCharmCE2017.3/config/scratches/scratch.py", line 18, in 
os.mkdir('abcd2/subdir')FileNotFoundError: [WinError 3] The system cannot find the path specified: 'abcd2/subdir'['.git', '1802.04103.pdf', '1st year', '2K16-CO-200', 'abc.txt', 'abcd', 'abcd1', 'abcd2', 'afcat']Process finished with exit code 1

NOTE: The line 18 code thrown an error for creating a directory along with a subdirectory because os.mkdir() don’t work in a tree fashion.

注意 :第18行代码在创建目录和子目录时引发错误,因为os.mkdir()不能以树的形式工作。

Os Mkdir

Python os mkdir() Function

Python os mkdir()函数

  1. os.rmdir() and os.removedirs(): same as os.mkdir() and os.makedirs() os.rmdir() will not remove the intermediate directory where as os.removedirs() will remove the intermediate directories. Observe the below code and output as continued with previous commands and directories.

    os.rmdir()和os.removedirs():与os.mkdir()和os.makedirs()相同os.rmdir()不会删除中间目录,因为os.removedirs()会删除中间目录。 观察下面的代码和输出,以及之前的命令和目录的继续。
os.rmdir('abcd')os.removedirs('abcd2/subdir')print(os.listdir())

OUTPUT:  [‘.git’, ‘1802.04103.pdf’, ‘1st year’, ‘2K16-CO-200’, ‘abc.txt’, ‘abcd1’, , ‘afcat’]

输出: ['.git','1802.04103.pdf','1st year','2K16-CO-200','abc.txt','abcd1','afcat']

  1. os.rename():to rename a file or a folder.In arguments pass the original file name first and then the new name of the file.

    os.rename():重命名文件或文件夹。在参数中先传递原始文件名,然后传递新文件名。
os.chdir('C:/Users/user/Desktop/temp')print(os.listdir())os.rename('xyz.txt','abc.txt')print(os.listdir())

OUTPUT:

输出:

Os Rename

Python os rename() function

Python OS os named()函数

  1. os.remove(): It removes the path of a file. It takes path string as a variable.

    os.remove():删除文件的路径。 它使用路径字符串作为变量。
import osos.chdir('C:/Users/user/Desktop/temp')print(os.listdir())os.chdir('C:/Users/user/Desktop/')os.remove('temp/abc.txt')os.chdir('C:/Users/user/Desktop/temp')print(os.listdir())

OUTPUT:

输出:

Os Remove

Python os remove() Function

Python os remove()函数

使用Python OS模块的优点 (Advantages of Using Python OS Module)

  • This module is useful if you want to make your programs platform-independent, i.e. with the use of python os module you can make your code run smoothly on linux as well as on windows without requiring any changes to be made.

    如果要使程序与平台无关,该模块很有用,即,使用python os模块,可以使您的代码在linux和Windows上平稳运行,而无需进行任何更改。
  • It represents the generic system functionality.

    它代表通用系统功能。

结论 (Conclusion)

At this point will be familiar with the python os module. In this article, we  learned the following:

至此,您将熟悉python os模块。 在本文中,我们了解了以下内容:

  • how to work with environment variables

    如何使用环境变量
  • change directories and discover your current working directory

    更改目录并发现您当前的工作目录
  • create and remove folders and files

    创建和删除文件夹和文件
  • rename files / folders

    重命名文件/文件夹
  • start a file with its associated application

    用其关联的应用程序启动文件
  • walk a directory

    走目录
  • work with paths

    使用路径

There are a lot of other functions in the os module that has not been discussed here because they are not commonly used. Be sure to read the documentation to see what else you can do with the python os module

os模块中还有许多其他功能在这里没有讨论,因为它们不常用。 请务必阅读文档以了解python os模块还可以做什么。

翻译自:

python中os函数

转载地址:http://htlzd.baihongyu.com/

你可能感兴趣的文章
小D课堂 - 新版本微服务springcloud+Docker教程_3-03CAP原理、常见面试题
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-04 SpringCloud微服务核心组件Eureka介绍和闭源后影响...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-05 服务注册和发现Eureka Server搭建实战...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-06 服务注册和发现之Eureka Client搭建商品服务实战...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-07 Eureka服务注册中心配置控制台问题处理...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-01 常用的服务间调用方式讲解
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-02 微服务调用方式之ribbon实战 订单调用商品服务...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-03 高级篇幅之Ribbon负载均衡源码分析实战...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-06 Feign核心源码解读和服务调用方式ribbon和Feign选择...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-05 微服务调用方式之feign 实战 订单调用商品服务...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-02 Netflix开源组件断路器
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-01分布式核心知识之熔断、降级
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-04 feign结合hystrix断路器开发实战下...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-03 feign结合hystrix断路器开发实战上...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_6-01 微服务网关介绍和使用场景
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-05熔断降级服务异常报警通知
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_6-03 高级篇幅之zuul常用问题分析
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-08 断路器监控仪表参数
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_6-02 springcloud网关组件zuul
查看>>
小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_2-1.快速搭建SpringBoot项目,采用Eclipse...
查看>>