Pathlib with_name 不重命名文件

Pathlib with_name does not rename file

文件未被 with_name() 重命名。使用 touch() 在路径 p 创建测试文件并使用 with_name().

更新 1.) 使用 Path 与 PurePath 是否存在问题? (没有)
2.) 是否需要使用更新的路径对象调用 replace() 来更改磁盘上的文件名? (是)

from pathlib import Path

p = Path('./test.txt')

p.touch()

print(f'p before: {p}')
# ==> p before: test.txt

# p is not updated
p.with_name('test_new.txt')
print(f'p after:  {p}')
# ==> p after: test.txt

仅使用 with_name() 更改路径不足以重命名文件系统上的相应文件。我能够通过使用更新的路径对象显式调用 .replace() 来重命名文件(见下文)。

p.replace(p.with_name('test_new.txt'))

根据 MisterMiyagi 上面的评论:

From the docs: "PurePath.with_name(name) Return a new path with the name changed. [...]". You have to assign the result of p.with_name(), or it is lost.

### WORKS ###
from pathlib import Path

# sets original path
p = Path('./test.txt')
print(p)
# ==> test.txt

# create file on disk
p.touch()

# prints updated path, but does not update p (due to immutability?)
print(p.with_name('test_new.txt')) 
# ==> test_new.txt

# p not updated
print(p)
# ==> test.txt

# assignment to q stores updated path
q = p.with_name('test_new.txt')
print(q)
# ==> test_new.txt

# file on disk is updated with new file name
p.replace(p.with_name('test_new.txt'))
# p.replace(q) # also works
print(p)
# ==> test_new.txt

path.with_name() 将生成一个新的 Path 对象。 path.rename()会生成一个新的Path对象,并调用新的Path对象的touch方法。

所以 path.rename() 才是正确的方法。