问题描述
我使用的是 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.
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()
使用 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)
参考:
这篇关于使用 pathlib (python 3) 重命名文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!