Search code examples
python-3.xpathlib

Pathlib with_name does not rename file


File is not renamed by with_name(). A test file is created at Path p using touch() and updated using with_name().

1.) Is there an issue caused by usage of Path vs PurePath? (no)
2.) Is it necessary to call replace() using the updated path object to change the file name on disk? (yes)

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

Solution

  • Just changing the path using with_name() is insufficient to rename the corresponding file on the filesystem. I was able to rename the file by explicitly calling .replace() with the updated path object (see below).

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

    Per MisterMiyagi's comment above:

    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