0
from pathlib import Path

file = Path(r"C:\Users\SerT\Desktop\a.txt")
print (file.name)

file.rename(file.with_name("b.txt"))
print (file.name)

i'd like to know why file.name prints out "a.txt" in both instances even though the file actually gets renamed in windows explorer

Ser.T
  • 51
  • 4
  • 3
    `with_name` and `rename` ***return a new `Path`***, they don't modify the existing `file` object. – deceze Jan 09 '21 at 19:25

2 Answers2

0

.rename doesn't modify the file object, instead it simply returns the new filepath. If you want to rename a file, you can set file equal to the file.rename method:

import os
from pathlib import Path

file = Path(r"C:\Users\SerT\Desktop\a.txt")
print (file.name)

file = file.rename(file.with_name("b.txt"))
print(file.name)
DapperDuck
  • 2,728
  • 1
  • 9
  • 21
0

The file is being renamed, but the original Path object (file in your case) is not changed itself.

Since Path.rename() returns a new Path object, to get the result you're expecting, do:

file = file.rename(file.with_name("b.txt"))
print(file.name)
aneroid
  • 12,983
  • 3
  • 36
  • 66