Python教程-Python OS模块

Python的OS模块提供了与操作系统之间交互的功能。它提供了许多有用的操作系统函数,用于执行基于操作系统的任务,并获取关于操作系统的相关信息。
OS模块属于Python的标准实用程序模块。该模块提供了一种可移植的方式来使用操作系统相关的功能。
Python的OS模块使我们能够处理文件和目录。
To work with the OS module, we need to import the OS module.
import os
OS模块中有一些函数,如下所示:
os.name()
这个函数提供导入的操作系统模块的名称。
当前,它注册了'posix'、'nt'、'os2'、'ce'、'java'和'riscos'。
示例
import os
print(os.name)
输出:
nt
os.mkdir()
os.mkdir()函数用于创建新目录。考虑以下示例。
import os
os.mkdir("d:\\newdir")
它将在D驱动器的路径中创建名为newdir的文件夹。
os.getcwd()
它返回文件的当前工作目录(CWD)。
示例
import os
print(os.getcwd())
输出:
C:\Users\Python\Desktop\ModuleOS
os.chdir()
os模块提供了chdir()函数来更改当前工作目录。
import os
os.chdir("d:\\")
输出:
d:\\
os.rmdir()
rmdir()函数通过绝对路径或相关路径删除指定的目录。首先,我们必须更改当前工作目录,然后删除文件夹。
示例
import os
# It will throw a Permission error; that's why we have to change the current working directory.
os.rmdir("d:\\newdir")
os.chdir("..")
os.rmdir("newdir")
os.error()
os.error()函数定义了操作系统级别的错误。在文件名无效或不可访问等情况下,它会引发OSError。
示例
import os
try:
# If file does not exist,
# then it throw an IOError
filename = 'Python.txt'
f = open(filename, 'rU')
text = f.read()
f.close()
# The Control jumps directly to here if
# any lines throws IOError.
except IOError:
# print(os.error) will <class 'OSError'>
print('Problem reading: ' + filename)
输出:
Problem reading: Python.txt
os.popen()
这个函数打开一个文件或从指定的命令,它返回一个连接到管道的文件对象。
示例
import os
fd = "python.txt"
# popen() is similar to open()
file = open(fd, 'w')
file.write("This is awesome")
file.close()
file = open(fd, 'r')
text = file.read()
print(text)
# popen() provides gateway and accesses the file directly
file = os.popen(fd, 'w')
file.write("This is awesome")
# File not closed, shown in next function.
输出:
This is awesome
os.close()
这个函数关闭与描述符fr相关联的文件。
示例
import os
fr = "Python1.txt"
file = open(fr, 'r')
text = file.read()
print(text)
os.close(file)
输出:
Traceback (most recent call last):
File "main.py", line 3, in
file = open(fr, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'Python1.txt'
os.rename()
可以使用函数os.rename()重命名文件或目录。如果用户有权更改文件,可以重命名文件。
示例
import os
fd = "python.txt"
os.rename(fd,'Python1.txt')
os.rename(fd,'Python1.txt')
输出:
Traceback (most recent call last):
File "main.py", line 3, in
os.rename(fd,'Python1.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'python.txt' -> 'Python1.txt'
os.access()
这个函数使用实际的uid/gid来测试调用用户是否对路径有访问权限。
示例
import os
import sys
path1 = os.access("Python.txt", os.F_OK)
print("Exist path:", path1)
# Checking access with os.R_OK
path2 = os.access("Python.txt", os.R_OK)
print("It access to read the file:", path2)
# Checking access with os.W_OK
path3 = os.access("Python.txt", os.W_OK)
print("It access to write the file:", path3)
# Checking access with os.X_OK
path4 = os.access("Python.txt", os.X_OK)
print("Check if path can be executed:", path4)
输出:
Exist path: False
It access to read the file: False
It access to write the file: False
Check if path can be executed: False