python基础(10)《python之OS》

本文详细介绍了Pythonos模块如何进行环境变量管理、目录和文件操作、执行系统命令,包括获取和设置环境变量、改变工作目录、文件列表、创建目录、删除文件等常见功能,以及跨平台路径操作和进程管理的相关示例。
摘要由CSDN通过智能技术生成

Python 的 os 模块提供了一种使用操作系统依赖功能的便捷方式。它允许你执行环境变量设置、目录操作、文件操作等一系列操作。下面将梳理一些常用的 os 模块功能以及相应的代码示例。需要注意的是,os 模块包含的功能非常广泛,因此这里仅覆盖一些比较常见的用法。

### 1. 环境操作
- 获取环境变量:`os.getenv()
` - 设置环境变量:`os.environ[key] = value

import os

# 获取环境变量
print(os.getenv('PATH'))

# 设置环境变量
os.environ['TEST_VAR'] = 'Test'
print(os.getenv('TEST_VAR'))

### 2. 目录和文件操作
- 获取当前工作目录:`os.getcwd()
` - 改变当前工作目录:`os.chdir()
` - 列出指定目录下的文件:`os.listdir()
` - 创建单层目录:`os.mkdir()
` - 递归创建多层目录:`os.makedirs()
` - 删除文件:`os.remove()

import os

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

# 改变当前工作目录
os.chdir('/tmp')
print(os.getcwd())

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

# 创建目录
os.mkdir('test')

# 递归创建目录
os.makedirs('test_dir/sub_dir')

# 删除文件
os.remove('test_file.txt')

### 3. 文件路径操作
- 分割路径名:`os.path.split()
` - 获取文件扩展名:`os.path.splitext()
` - 检查路径是否存在:`os.path.exists()

import os

# 分割路径名
head, tail = os.path.split('/home/user/file.txt')
print(head, tail)

# 获取文件扩展名
root_ext = os.path.splitext('/path/to/somefile.txt')
print(root_ext)

# 检查路径是否存在
print(os.path.exists('/path/to/file'))

### 4. 系统操作
- 执行系统命令:`os.system()

import os

# 在 Linux 或 Mac 系统下
os.system('ls')

# 在 Windows 系统下
os.system('dir')

 ### 路径操作

- 跨平台的路径操作

import os

# 连接路径
path = os.path.join("/mydir", "myfile.txt")
print(path)

# 分割路径
dir_name, file_name = os.path.split(path)
print(dir_name)
print(file_name)

# 检查路径是否存在
print(os.path.exists(path))

# 获取文件大小
print(os.path.getsize(path))

# 检查是否为文件
print(os.path.isfile(path))

# 检查是否为目录
print(os.path.isdir(path))

 ### 文件和目录管理

- 创建、重命名、删除文件和目录

import os

# 创建目录
os.mkdir("newdir")

# 重命名目录
os.rename("newdir", "newdir_renamed")

# 删除目录
os.rmdir("newdir_renamed")

# 创建临时文件夹和文件
import tempfile

temp_dir = tempfile.mkdtemp()
print(temp_dir)

temp_file = tempfile.mkstemp()
print(temp_file)

### 进程管理

- 在Python中,`os`模块也提供了启动和与操作系统级进程交互的方法。

import os

# 使用系统命令
os.system('echo Hello World')

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

# 改变当前工作目录
os.chdir('/path/to/new/directory')
print(os.getcwd())

### 其他常用功能

- 获取当前工作目录:`os.getcwd()
` - 改变当前工作目录:`os.chdir('/new/dir')
` - 列出指定目录下的文件和子目录:`os.listdir('/path/to/dir')
` - 删除文件:`os.remove('file_name')
` - 执行系统命令:`os.system('command')
` - 获取文件的访问和修改时间:`os.path.getatime(file)``os.path.getmtime(file) 

import os    
os.mkdir('new_directory')
#- **递归创建目录**:  
os.makedirs('new_directory/another_directory')
#- **列出目录内容**:   
print(os.listdir('.')) 
#- **删除文件**:    
os.remove('file.txt') 
#- **重命名文件或目录**: 
os.rename('old_name.txt', 'new_name.txt')
#- **获取当前工作目录**: 
print(os.getcwd())    
#**改变当前工作目录**: 
os.chdir('/path/to/directory')  
# **删除目录**:
os.rmdir('directory_name')
### 文件属性- **获取文件属性**: 
stat_info = os.stat('somefile.txt')    
print(stat_info) 
#**检查权限**: 
print(os.access('somefile.txt', os.R_OK)) # Check for read access    
print(os.access('somefile.txt', os.W_OK)) # Check for write access   
### 环境变量- **获取环境变量**: 
print(os.getenv('PATH'))
# **设置环境变量**:
os.environ['NEW_VAR'] = 'value'  
# 进程管理- **执行系统命令**:  
os.system('ls')
#**创建子进程**:    
# - 使用 ``os.fork()`()` (在Unix/Linux系统上可用): 
pid = os.fork()        
if pid > 0:            
    print('I am the parent, my child is', pid)        
else:            
    print('I am the child')
#使用 ``os.spawn*`系列函数来启动一个新程序:
os.spawnlp(os.P_NOWAIT, 'ls', 'ls', '-l') 
#路径操作- **路径拼接**: 
print(os.path.join('/home', 'user', 'docs'))
#- **路径分割**:
print(os.path.split('/home/user/docs/file.txt'))
# **检查文件或目录是否存在**:
print(os.path.exists('/path/to/file'))
# **获取绝对路径**: 
print(os.path.abspath('./relative/path'))
# **检查是否是文件**: 
print(os.path.isfile('/path/to/file'))
# **检查是否是目录**: 
print(os.path.isdir('/path/to/directory'))

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

石明亮(JT)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值