python os rename用法_Python os.rename()用法及代码示例

Python中的OS模块提供了与操作系统进行交互的功能。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的功能的便携式方法。

os.rename()Python中的方法用于重命名文件或目录。

此方法将源文件/目录重命名为指定的目标文件/目录。

用法: os.rename(source, destination, *, src_dir_fd = None, dst_dir_fd = None)

参数:

source:代表文件系统路径的path-like对象。这是要重命名的源文件路径。

destination:代表文件系统路径的path-like对象。

src_dir_fd(可选):引用目录的文件描述符。

dst_dir_fd(可选):引用目录的文件描述符。

返回类型:此方法不返回任何值。

代码1:用于os.rename()方法

# Python program to explain os.rename() method

# importing os module

import os

# Source file path

source = 'GeeksforGeeks/file.txt'

# destination file path

dest = 'GeekforGeeks/newfile.txt'

# Now rename the source path

# to destination path

# using os.rename() method

os.rename(source, dest)

print("Source path renamed to destination path successfully.")

输出:

Source path renamed to destination path successfully.

代码2:处理可能的错误

# Python program to explain os.rename() method

# importing os module

import os

# Source file path

source = './GeeksforGeeks/file.txt'

# destination file path

dest = './GeeksforGeeks/dir'

# try renaming the source path

# to destination path

# using os.rename() method

try :

os.rename(source, dest)

print("Source path renamed to destination path successfully.")

# If Source is a file

# but destination is a directory

except IsADirectoryError:

print("Source is a file but destination is a directory.")

# If source is a directory

# but destination is a file

except NotADirectoryError:

print("Source is a directory but destination is a file.")

# For permission related errors

except PermissionError:

print("Operation not permitted.")

# For other errors

except OSError as error:

print(error)

输出:

Source is a file but destination is a directory.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值