Python OS模块提供了在用户和操作系统之间建立交互的函数。它提供了许多有用的OS函数,这些函数可用于执行基于OS的任务并获取有关操作系统的相关信息。
该操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的函数的便携式方法。
Python OS模块使无涯教程可以处理文件和目录。
链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-os-module.html
来源:LearnFk无涯教程网
To work with the OS module, we need to import the OS module. import os
OS模块中有一些函数,如下所示:
此函数提供了它导入的操作系统模块的名称。
当前,它注册" posix"," nt"," os2"," ce"," java"和" riscos"。
import os print(os.name)
输出:
nt
os.mkdir()函数用于创建新目录。考虑以下示例。
import os os.mkdir("d:\\newdir")
它将在名为文件夹newdir的D驱动器中的函数的字符串参数中创建路径的新目录。
它返回文件的当前工作目录(CWD)。
import os print(os.getcwd())
输出:
C:\Users\Python\Desktop\ModuleOS
os 模块提供了 chdir()函数来更改当前工作目录。
import os os.chdir("d:\\")
输出:
d:\\
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()函数定义操作系统级别的错误。如果文件名和路径等无效或无法访问,则会引发OSError。
import os try: # 如果文件不存在,然后它抛出一个ioerror异常 filename = 'Python.txt' f = open(filename, 'rU') text = f.read() f.close() # 如果,控制直接跳转到这里任何行都抛出ioError。 except IOError: # print(os.error) will <class 'OSError'> print('Problem reading: ' + filename)
输出:
Problem reading: Python.txt
此函数打开文件或通过指定的命令打开文件,并返回连接到管道的文件对象。
import os fd = "python.txt" # popen() 类似于open() file = open(fd, 'w') file.write("This is awesome") file.close() file = open(fd, 'r') text = file.read() print(text) # popen() 直接访问文件 file = os.popen(fd, 'w') file.write("This is awesome")
输出:
This is awesome
此函数关闭描述符为 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()重命名文件或目录。如果用户有权更改文件,则可以重命名该文件。
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'
此函数使用真实的 uid/gid 来测试调用用户是否有权访问该路径。
import os import sys path1 = os.access("Python.txt", os.F_OK) print("Exist path:", path1) # 使用OS.R_OK检查访问 path2 = os.access("Python.txt", os.R_OK) print("It access to read the file:", path2) # 使用OS.W_OK检查访问 path3 = os.access("Python.txt", os.W_OK) print("It access to write the file:", path3) # 使用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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)