使用 pathlib (python 3) 重命名文件扩展名 [英] Renaming file extension using pathlib (python 3)

查看:30
本文介绍了使用 pathlib (python 3) 重命名文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Windows 10 和 winpython.我有一个扩展名为 .dwt 的文件(它是一个文本文件).我想将此文件的扩展名更改为 .txt.

I am using windows 10 and winpython. I have a file with a .dwt extension (it is a text file). I want to change the extension of this file to .txt.

我的代码不会抛出任何错误,但不会更改扩展名.

My code does not throw any errors, but it does not change the extension.

from pathlib import Path

filename = Path("E:\\seaborn_plot\\x.dwt")

print(filename)

filename_replace_ext = filename.with_suffix('.txt')

print(filename_replace_ext)

在winpython的ipython窗口输出中打印出预期的结果(如下图):

Expected results are printed out (as shown below) in winpython's ipython window output:

E:\seaborn_plot\x.dwt

E:\seaborn_plot\x.dwt

E:\seaborn_plot\x.txt

E:\seaborn_plot\x.txt

但是当我寻找一个带有重命名扩展名的文件时,扩展名没有改变,只有原始文件存在.我怀疑 Windows 文件权限.

But when I look for a file with a renamed extension, the extension has not been changed, only the original file exists. I suspect windows file permissions.

推荐答案

您必须实际重命名文件,而不仅仅是打印出新名称.

You have to actually rename the file not just print out the new name.

  1. 使用 Path.rename()

 from pathlib import Path
 my_file = Path("E:\\seaborn_plot\\x.dwt")
 my_file.rename(my_file.with_suffix('.txt'))

注意:要替换存在的目标,请使用 Path.replace()

Note: To replace the target if it exists use Path.replace()

  1. 使用 os.rename()

 import os
 my_file = 'E:\\seaborn_plot\\x.dwt'
 new_ext = '.txt'
 # Gets my_file minus the extension
 name_without_ext = os.path.splitext(my_file)[0]
 os.rename(my_file, name_without_ext + new_ext)

参考:

  1. os.path.splitext(path)
  2. PurePath.with_suffix(后缀)

这篇关于使用 pathlib (python 3) 重命名文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆