Python OS函数模块

Python OS函数模块

Python OS函数模块

  Python 中的 OS 模块提供了与操作系统交互的函数。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。

  os 和 os.path 模块包含许多与文件系统交互的函数。本文晓得博客为你介绍Python OS函数模块。

  推荐:如何将Python添加到Path环境变量

处理当前工作目录

  将当前工作目录(CWD)视为 Python 运行的文件夹。每当仅通过名称调用文件时,Python 假定它从 CWD 开始,这意味着仅当文件位于 Python 的 CWD 中时,仅名称引用才会成功。

python处理当前工作目录

  注意:运行 Python 脚本的文件夹称为当前目录。这不是 Python 脚本所在的路径。

获取当前工作目录

  要获取当前工作目录的位置,可以使用os.getcwd() 。

import os

cwd = os.getcwd()

print("Current working directory:", cwd)

输出:
Current working directory: C:\WINDOWS\system32
更改当前工作目录

  要更改当前工作目录 (CWD),使用os.chdir()方法。此方法将 CWD 更改为指定路径。它只需要一个参数作为新的目录路径。

  注意:当前工作目录是Python脚本运行所在的文件夹。

import os

def current_path():
    print("Current working directory before")
    print(os.getcwd())
    print()

current_path()
os.chdir('../')
current_path()

输出:
Current working directory before
C:\WINDOWS\system32

Current working directory before
C:\WINDOWS

  推荐:Python String format()教程

创建目录

  OS 模块中有不同的方法可用于创建目录。这些是 os.mkdir() 和 os.makedirs()

python创建目录
使用 os.mkdir()

  Python OS函数模块的 os.mkdir() 方法用于创建一个名为 path 的目录,具有指定的数字模式。如果要创建的目录已经存在,则此方法会引发 FileExistsError。

import os

directory = "xiaodeblog"
parent_dir = "D:/Pycharm projects/"
path = os.path.join(parent_dir, directory)
os.mkdir(path)
print("Directory '% s' created" % directory)

directory = "Numpy"
parent_dir = "D:/Pycharm projects"
mode = 0o666
path = os.path.join(parent_dir, directory)

os.mkdir(path, mode)
print("Directory '% s' created" % directory)

输出:
Directory 'xiaodeblog' created
Directory 'Numpy' created

  推荐:Python不等于!=运算符示例

使用 os.makedirs()

  Python 中的 os.makedirs() 方法用于递归创建目录。这意味着在创建叶目录时,如果缺少任何中间级目录,os.makedirs() 方法将创建它们。

import os

directory = "generatepress"
parent_dir = "D:/Pycharm projects/pythonthree/Authors"
path = os.path.join(parent_dir, directory)
os.makedirs(path)

print("Directory '% s' created" % directory)

directory = "c"
parent_dir = "D:/Pycharm projects/pythonthree/a/b"
mode = 0o666
path = os.path.join(parent_dir, directory)
os.makedirs(path, mode)

print("Directory '% s' created" % directory)

输出:
Directory 'generatepress' created
Directory 'c' created

使用Python列出文件和目录

  Python 中的os.listdir()方法用于获取指定目录下所有文件和目录的列表。如果我们不指定任何目录,那么将返回当前工作目录中的文件和目录列表。

import os

path = "/"
dir_list = os.listdir(path)

print("Files and directories in '", path, "' :")
print(dir_list)

输出:
Files and directories in ' / ' :
['$360Section', '$Recycle.Bin', '$WinREAgent', '$WINRE_BACKUP_PARTITION.MARKER', '360SANDBOX', 'Boot', 'bootmgr', 'BOOTNXT', 'BOOTSECT.BAK', 'bootTel.dat', 'Documents and Settings', 'DumpStack.log', 'DumpStack.log.tmp', 'EFI', 'hiberfil.sys', 'KRECYCLE', 'MAMP', 'MAMPPRO', 'MyDrivers', 'NVIDIA', 'pagefile.sys', 'PerfLogs', 'Program Files', 'Program Files (x86)', 'ProgramData', 'Recovery', 'swapfile.sys', 'System Volume Information', 'Users', 'Windows', 'xampp']

  推荐:如何在Python中设置虚拟环境

使用Python删除目录或文件

  OS 模块证明了在 Python 中删除目录和文件的不同方法。这些是使用 os.remove()、使用 os.rmdir()

使用 os.remove()

  Python 中的 os.remove() 方法用于移除或删除文件路径。此方法不能移除或删除目录。如果指定的路径是目录,则该方法将引发 OSError。

使用os.rmdir()

  Python OS函数模块的 os.rmdir() 方法用于移除或删除一个空目录。如果指定的路径不是空目录,将引发 OSError。

常用函数

Python OS函数模块

  1、os.name:这个函数给出了导入的操作系统依赖模块的名称。目前已注册以下名称:“posix”、“nt”、“os2”、“ce”、“java”注意:它可能会在不同的解释器上给出不同的输出,

  2、os.error:此模块中的所有函数在无效或不可访问的文件名和路径,或其他具有正确类型但不被操作系统接受的参数的情况下引发 OSError。os.error 是内置 OSError 异常的别名。

  3、os.popen():此方法打开一个到命令或从命令的管道。可以读取或写入返回值,具体取决于模式是“r”还是“w”。

  4、os.close():关闭文件描述符fd。使用 open() 打开的文件只能通过 close() 关闭。但是通过 os.popen() 打开的文件可以用 close() 或 os.close() 关闭。如果我们尝试关闭使用 open() 打开的文件,使用 os.close(),Python 会抛出 TypeError。

  5、os.rename():使用函数os.rename() 可以将文件old.txt 重命名为new.txt。仅当文件存在且用户有足够的权限更改文件时,文件名才会更改。

  6、os.remove():使用 Os 模块,我们可以使用 remove() 方法删除系统中的文件。要删除文件,我们需要将文件名作为参数传递。

  7、os.path.exists():此方法将通过将文件名作为参数传递来检查文件是否存在。OS 模块有一个名为 PATH 的子模块,我们可以使用它执行更多功能。

  8、os.path.getsize():在这个方法中,python 将以字节为单位给我们文件的大小。要使用此方法,我们需要将文件名作为参数传递。

  推荐:常用的50个Python模块列表

总结

  以上是晓得博客为你介绍的Python OS函数模块的全部内容,希望对你学习Python有所帮助,如果有任何问题,可随时联系我们。

  推荐:零基础如何开始学习Python


晓得博客,版权所有丨如未注明,均为原创
晓得博客 » Python OS函数模块

转载请保留链接:https://www.pythonthree.com/os-module-python-examples/

滚动至顶部