亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python文件管理:轻松重命名与删除文件

Python重命名与删除文件

Python用os模块内置函数重命名、删除文件,是文件系统管理核心操作。本教程分步讲解。

重命名文件

用os.rename()重命名,接受两参数:当前文件名、新文件名。

语法

os.rename(current_file_name, new_file_name)

参数

示例

import os
current_name = "oldfile.txt"
new_name = "newfile.txt"
os.rename(current_name, new_name)
print(f"文件 '{current_name}' 重命名为 '{new_name}' 成功。")

输出:

文件 'oldfile.txt' 重命名为 'newfile.txt' 成功。

删除文件

用os.remove()删除指定文件名文件。

语法

os.remove(file_name)

参数

需删除文件的文件名。

示例

import os
file_to_delete = "file_to_delete.txt"
os.remove(file_to_delete)
print(f"文件 '{file_to_delete}' 删除成功。")

输出:

文件 'file_to_delete.txt' 删除成功。

Python

  1. Real Python互动测验:检验学习进度、提升Python技能
  2. 掌握 IPython:提升 Python 开发效率
  3. 精通 Python time 模块:函数、结构体与实战示例
  4. Python str.count() 完全指南:统计字符与子串出现次数实战
  5. Python NumPy 矩阵运算:转置、加法、乘法与切片实战指南
  6. 掌握Python脚本运行:全面分步指南
  7. Python 与 MySQL:数据库连接、创建与 CRUD 操作实战指南
  8. Python 文件 I/O:掌握文件操作、读写与管理
  9. Python打造井字游戏:分步代码教程
  10. Python collections.Counter:高效计数、更新与算术运算
  11. 精通 Python 异常处理:try、except、finally 与 raise 高效用法
  12. Python 开发环境搭建完整指南:跨平台安装与配置