Python os库函数

时间:2020-02-23 14:43:07  来源:igfitidea点击:

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

Python import os

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

import os  # importing the complete os module

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

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

码:

import os

print(dir(os))

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

OS模块的常用功能

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

  • 操作目录:

  • chdir()

  • getcwd()

  • listdir()

  • mkdir()

  • makedirs()

  • rmdir()

  • removeirs()

  • 删除文件:

  • remove()

  • 重命名文件/目录:

  • rename()

  • 使用多个进程:

  • system()

  • popen()

  • close()

  • walk()

  • 用户标识和进程标识:

  • getgid(),os.getuid(),os.getpid()

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

  • error

  • stat()

  • 跨平台os属性:

  • name

  • 访问环境变量:

  • environ

常用功能说明和用法

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

输出操作系统名称

  • os.error:这是I/O错误和OSError的环境错误类,当任何函数返回任何与系统相关的错误时引发。
    当在代码行中触发任何无效或者不可访问的文件时,每个或者模块函数均会返回这些错误。
import os

try:
    filename = 'abcd2.txt'
    f = open(filename, 'r')
    text = f.read()
    f.close()

except os.error:

    print('Problem reading: ' + filename)

输出:Os错误

  • os.system():执行一个shell命令。
 cmd = "git --version"

returned_value = os.system(cmd)  # returns the exit code in unix
print('returned value:', returned_value)

输出:Linux操作系统示例

  • os.environ():这是一个对象的值,该对象返回所有用户环境变量的所有目录。
    " HOME"目录环境变量
import os

os.chdir('C:/Users/user/Desktop/temp')
# returns all the environment variables
print(os.environ)
# to get in particular
print(os.environ.get('TEMP'))

输出:Linux os.environ示例

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

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

  • os.chdir():更改目录。
os.chdir('C:/Users/user/.PyCharmCE2016.3/')

print(os.getcwd())

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

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

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

  • os.popen(command [,mode [,bufsize]]):它打开到命令的管道。
    它返回连接到管道的打开文件对象,可以根据模式是" r"(默认)还是" w"来进行读取或者写入。
import os

fd = "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 directly
file = os.popen(fd, 'w')
file.write("Hello")
  • os.close():关闭文件描述符fd。

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

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

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

  • 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 time
print(os.stat('abcd1').st_mtime)

# this returns the size of the file in bytes
print(os.stat('abcd1').st_size)
  • os.walk():这是一个生成器,它在遍历目录树时会产生两个三个值,并且会遍历每个目录并生成目录路径,该路径内的直接目录和该路径内的文件。

跟踪所有目录很有用。

os.chdir('C:/Users/user/Desktop/temp')

# returns a 3-tuple
for dirpath, dirname, filename in os.walk('C:/Users/user/Desktop/temp'):
    print('Current path: ',dirpath)
    print('Directories: ', dirname)
    print('Files: ', filename)
    print()
  • os.mkdir()和os.makedirs():创建新目录。

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

输出:

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

Traceback (most recent call last):

File "C:/Users/user/.PyCharmCE2016.3/config/scratches/scratch.py", line 18, in <module>

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

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

Python os mkdir()函数

  • os.rmdir()和os.removedirs():与os.mkdir()和os.makedirs()相同os.rmdir()不会删除中间目录,因为os.removedirs()会删除中间目录。
    观察以下代码,并输出与先前命令和目录相同的内容。
os.rmdir('abcd')
os.removedirs('abcd2/subdir')

print(os.listdir())

输出:[.git"," 1802.04103.pdf","第一年"," 2K16-CO-200"," abc.txt"," abcd1"," afcat"]

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

print(os.listdir())

os.rename('xyz.txt','abc.txt')

print(os.listdir())
  • os.remove():删除文件的路径。
    它使用路径字符串作为变量。
import os

os.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())

使用Python OS模块的优点

  • 如果您想使程序与平台无关,即使用python os模块,则此模块很有用,即可以使代码在linux和Windows上平稳运行,而无需进行任何更改。

  • 它代表通用系统功能。