【Python 中的 OS 模块示例(实例)(Example)】

《Python 中的 OS 模块示例》

Python 中的 OS 模块提供了与操作系统交互的函数。OS 属于 Python 的标准实用模块。该模块提供了一种使用依赖于操作系统功能的便携方式。

osos.path 模块包含许多与文件系统交互的函数。

Python - OS 模块函数

这里我们将讨论 Python os 模块的一些重要函数:

  • 处理当前工作目录
  • 创建目录
  • 使用 Python 列出文件和目录
  • 使用 Python 删除目录或文件

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

示例:这段代码使用 os 模块获取并打印 Python 脚本的当前工作目录(CWD)。它使用 os.getcwd() 检索 CWD 并将其打印到控制台。

import os 
cwd = os.getcwd() 
print("Current working directory:", cwd) 

更改当前工作目录

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

示例:该代码检查并显示更改目录前后的当前工作目录(CWD)。它提供了一个在 Python 中处理当前工作目录的简单示例。

import os 
def current_path(): 
    print("Current working directory before") 
    print(os.getcwd()) 
    print() 
current_path() 
os.chdir('../') 
current_path() 

创建目录

在 OS 模块中有不同的方法可用于创建目录,例如:

使用 os.mkdir()

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

示例:这段代码在指定目录中创建了两个目录:“GeeksforGeeks”和“Geeks”。

import os
directory = "GeeksforGeeks"
parent_dir = "D:/Pycharm projects/"
path = os.path.join(parent_dir, directory)

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

使用 os.makedirs()

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

示例:此代码在不同的父目录中创建了两个目录“Nikhil”和“c”。

import os
directory = "Nikhil"
parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"
path = os.path.join(parent_dir, directory)
os.makedirs(path)
print("Directory '% s' created" % directory)
directory = "c"
parent_dir = "D:/Pycharm projects/GeeksforGeeks/a/b"
mode = 0o666
path = os.path.join(parent_dir, directory)
os.makedirs(path, mode)
print("Directory '% s' created" % directory)

列出 Python 中的文件和目录

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

示例:此代码列出根目录(“/”)中的所有文件和目录。

import os 
path = "/"
dir_list = os.listdir(path) 
print("Files and directories in '", path, "' :") 
print(dir_list) 

使用 Python 删除目录或文件

OS 模块提供了不同的方法来在 Python 中删除目录和文件,例如:

使用 os.remove()

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

示例:假设文件夹中的文件为:

import os 
file = 'file1.txt'
location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/"
path = os.path.join(location, file) 
os.remove(path) 

使用 os.rmdir()

Python 中的 os.rmdir() 方法用于删除空目录。如果指定的路径不是空目录,则会引发 OSError

示例:假设目录为 :

import os 
directory = "Geeks"
parent = "D:/Pycharm projects/"
path = os.path.join(parent, directory) 
os.rmdir(path) 

常用函数

使用 os.name 函数

此函数给出导入的依赖于操作系统的模块的名称。目前已注册的名称有:‘posix’、‘nt’、‘os2’、‘ce’、‘java’ 和 ‘riscos’ 。

import os
print(os.name)

使用 os.error 函数

此模块中的所有函数在文件名和路径无效或无法访问,或者其他参数类型正确但操作系统不接受时,都会引发 OSErroros.error 是内置 OSError 异常的别名。

import os
try:
    filename = 'GFG.txt'
    f = open(filename, 'rU')
    text = f.read()
    f.close()
except IOError:
  print('Problem reading: ' filename)

使用 os.popen() 函数

此方法打开到命令的管道。根据模式是’r’还是’w’,返回值可以读取或写入。

语法: os.popen(command[, mode[, bufsize]])

参数 modebufsize 不是必需的参数,如果未提供,则模式默认为’r’。

import os
fd = "GFG.txt"

file = open(fd, 'w')
file.write("Hello")
file.close()
file = open(fd, 'r')
text = file.read()
print(text)

file = os.popen(fd, 'w')
file.write("Hello")

使用 os.close() 函数

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

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

使用 os.rename() 函数

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

import os
fd = "GFG.txt"
os.rename(fd,'New.txt')
os.rename(fd,'New.txt')

使用 os.path.exists() 函数

此方法通过传递文件名作为参数来检查文件是否存在。OS 模块有一个名为 PATH 的子模块,通过它我们可以执行更多功能。

import os 
#importing os module

result = os.path.exists("file_name") #giving the name of the file as a parameter.

print(result)

使用 os.path.getsize() 函数

os.path.getsize() 函数中,Python 将以字节为单位给出文件的大小。要使用此方法,我们需要传递文件名作为参数。

import os #importing os module
size = os.path.getsize("filename")
print("Size of the file is", size," bytes.")

常见问题

什么是 Python 中的 OS 模块?

Python 中的 os 模块提供了一种与操作系统交互的方式。它包括处理文件操作、目录管理和其他与操作系统相关的任务的函数。

import os

# 获取当前工作目录
current_directory = os.getcwd()
print(current_directory)

# 列出当前目录中的文件和目录
files = os.listdir('.')
print(files)

什么是 OS 包?

OS 包通常是指设计用于提供与操作系统交互的标准化方式的模块和工具的集合。在 Python 的上下文中,os 包/模块提供了与操作系统交互的功能,允许文件和目录操作、环境变量访问和进程管理。

Python 中的 OS 名称是什么?

os.nameos 模块的一个属性,提供了导入的依赖于操作系统的模块的名称。这可以帮助识别代码运行的平台。

import os

# 获取 OS 名称
os_name = os.name
print(os_name)  # 输出:'posix'、'nt'、'java' 等

Python 中的 OS 进程是什么?

Python 中的 OS 进程是指 os 模块中允许与系统进程交互的函数。这包括创建、终止和管理进程的函数。例如,os.system() 可用于运行 shell 命令。

import os

# 执行系统命令
os.system('echo Hello, World!')

什么是 Python 的 IO 模块?

Python 中的 io 模块提供了处理各种类型的输入/输出(I/O)的主要设施。它用于处理文件读写操作以及其他与 I/O 相关的任务。此模块定义了处理二进制和文本 I/O 的基类和函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值