python中os库部分用法

1. os.path.splitext()

  • os.path.splitext() 将文件名和扩展名分开

例子:

程序:
import os
file_list = os.listdir('./')
for file_name in file_list:
    print('完整的文件名:',file_name)
    file_splitext = os.path.splitext(file_name)
    print('名字和后缀:',file_splitext)
    print('后缀:',file_splitext[1])

结果:
完整的文件名: getWordFreqbyUID.py
名字和后缀: ('getWordFreqbyUID', '.py')
后缀: .py
完整的文件名: word_frequency.cp38-win_amd64.pyd
名字和后缀: ('word_frequency.cp38-win_amd64', '.pyd')
后缀: .pyd
完整的文件名: backups-code  #这是个文件夹
名字和后缀: ('backups-code', '')
后缀: 

2. os.path.split()

### Python `os` 的功能与用法 #### 什么是 `os` 模块? Python 的标准中的 `os` 模块提供了许多函数来与操作系统进行交互。它允许开发者执行诸如文件操作、目录管理以及进程控制等任务。 #### 常见功能 以下是 `os` 模块的一些常见功能及其对应的示例代码: 1. **打开文件** 使用 `os.open()` 可以通过指定路径和模式(如只读、写入等)来打开一个文件,并返回该文件的描述符。 ```python import os # 打开文件,O_RDONLY 表示只读模式 file_descriptor = os.open("/path/to/file", os.O_RDONLY) print(f"File descriptor: {file_descriptor}") ``` 2. **截断文件大小** 函数 `os.ftruncate(fd, length)` 将由文件描述符 `fd` 指定的文件长度设置为给定的字节数。 ```python import os # 截断文件到 100 字节 fd = os.open("/path/to/file", os.O_RDWR) os.ftruncate(fd, 100) # 文件被裁剪至 100 字节 os.close(fd) # 关闭文件描述符 ``` 3. **更改当前工作目录** 使用 `os.chdir(path)` 来改变当前的工作目录。 ```python import os current_directory = os.getcwd() # 获取当前工作目录 print(f"Current directory before change: {current_directory}") new_directory = "/new/path" os.chdir(new_directory) # 更改工作目录 updated_directory = os.getcwd() print(f"Updated working directory: {updated_directory}") ``` 4. **创建新目录** 调用 `os.mkdir(path[, mode])` 创建一个新的子目录。 ```python import os dir_path = "/tmp/new_dir" try: os.mkdir(dir_path) # 如果不存在则创建目录 print(f"Directory created at path: {dir_path}") except FileExistsError as e: print(f"Directory already exists or an error occurred: {e}") ``` 5. **删除现有目录** 利用 `os.rmdir(path)` 删除空目录。 ```python import os dir_to_remove = "/tmp/new_dir" if os.path.exists(dir_to_remove): os.rmdir(dir_to_remove) # 删除目录 print(f"Removed the directory: {dir_to_remove}") else: print("The specified directory does not exist.") ``` 6. **环境变量访问** 访问系统的环境变量可以通过 `os.environ` 实现。 ```python import os env_var_value = os.getenv('HOME') # 获取 HOME 环境变量值 print(f"The value of 'HOME': {env_var_value}") ``` 7. **获取系统信息** 查询有关运行程序的操作系统的信息。 ```python import os system_name = os.uname().sysname # 当前操作系统名称 (Unix-like systems only) node_name = os.uname().nodename # 主机名 release_info = os.uname().release # 发布版本号 machine_type = os.uname().machine # 处理器架构 processor_details = os.uname().version # 版本详情 print(f"System Info:\nName={system_name}\nNode Name={node_name}\nRelease={release_info}\nMachine Type={machine_type}\nProcessor Details={processor_details}")[^4] ``` 8. **遍历目录树** 使用 `os.walk(top, topdown=True)` 遍历整个目录结构。 ```python import os root_dir = '/some/directory' for root, dirs, files in os.walk(root_dir): print(f"Root Directory: {root}, Subdirectories: {dirs}, Files: {files}") ``` 9. **重命名文件或目录** 移动或者重命名文件/目录可调用 `os.rename(src, dst)` 方法完成。 ```python import os old_file = "/old/path/to/file.txt" new_file = "/new/path/to/file_renamed.txt" os.rename(old_file, new_file) # 改变文件位置或名字 print(f"Renamed '{old_file}' to '{new_file}'.") ``` 以上列举了一些常用方法,更多细节可以查阅官方文档或其他权威资料[^5]。 --- #### 官方文档链接 对于更深入的学习,建议参考 [Python 官方文档](https://docs.python.org/zh-cn/3/library/os.html),其中包含了完整的 API 描述和技术说明。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值