Python Forum
How does pathlib.Path.rename work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How does pathlib.Path.rename work?
#1
I want to write a small script for a friend who has a bunch of images restored after deletion ( 50 gigs ) and I'm trying to use the pathlib module for this. But the renamed files are moved into the working directory. How does rename method work?

Here is the initial code:

path = Path(args.path)
files = (f for f in path.rglob('*') if f.is_file())

for f in files:
    ext = f.suffix
    if ext != '.py':
        stats = f.stat()
        name = Path(datetime.fromtimestamp(stats.st_mtime).strftime('%Y%m%d-%H%M%S'))
        f.rename(name)
The directory contains two more with the images inside them. When I run the code all images are renamed and moved to the working directory ( the root scan directory for example. The default path is '.').
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#2
you can use f.name directly, since f is a pathlib object
Reply
#3
I am doing just that but the files are moved to the working directory.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
How about RTM
https://docs.python.org/3/library/pathli...ath.rename
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#5
@volcano63, if you look at the code snippet I am using Path.rename method. But it's not happening what I expect.
This is the directory structure:
root_dir
   |-dir_1
   |   |-img_1
   |   |-img_2
   |   |-...
   |
   |-dir_2
       |-img_1
       |-img_2
       |_...
When I run the script this happens:
root_dir
   |-dir_1
   |-dir_2
   |-img_1
   |-img_2
   |-...
I can do it with os module but I want to know how pathlib works and what it's capable of.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#6
here is a pathlib data structure for an application I am working on.
It spans many directories and sub directories and may or may not be of any use for your application, but I offer it just the same:
BizPaths.py:
# Code files found here: 
from pathlib import Path
import os
import inspect


class BizPaths:
    def __init__(self):
        os.chdir(os.path.dirname(__file__))

        self.homepath = Path('.')
        self.rootpath = self.homepath / '..'

        self.datapath = self.rootpath / 'data'
        self.datapath.mkdir(exist_ok=True)

        self.dbpath = self.datapath / 'database'
        self.dbpath.mkdir(exist_ok=True)

        self.jsonpath = self.datapath / 'json'
        self.jsonpath.mkdir(exist_ok=True)

        self.rawdatapath = self.datapath / 'RawData'
        self.rawdatapath.mkdir(exist_ok=True)

        self.countrypath = self.rawdatapath / 'Country'
        self.countrypath.mkdir(exist_ok=True)

        self.usapath = self.countrypath / 'USA'
        self.usapath.mkdir(exist_ok=True)

        self.Countries = {
            'USA': {
                'Alaska': self.usapath / 'Alaska',
                'Alabama': self.usapath / 'Alabama',
                'Arkansas': self.usapath / 'Arkansas',
                'AmericanSamoa': self.usapath / 'AmericanSamoa',
                'Arizona': self.usapath / 'Arizona',
                'California': self.usapath / 'California',
                'Colorado': self.usapath / 'Colorado',
                'Connecticut': self.usapath / 'Connecticut',
                'WashingtonDC': self.usapath / 'WashingtonDC',
                'Delaware': self.usapath / 'Delaware',
                'Florida': self.usapath / 'Florida',
                'FederatedStatesOfMicronesia': self.usapath / 'FederatedStatesOfMicronesia',
                'Georgia': self.usapath / 'Georgia',
                'Guam': self.usapath / 'Guam',
                'Hawaii': self.usapath / 'Hawaii',
                'Iowa': self.usapath / 'Iowa',
                'Idaho': self.usapath / 'Idaho',
                'Illinois': self.usapath / 'Illinois',
                'Indiana': self.usapath / 'Indiana',
                'Kansas': self.usapath / 'Kansas',
                'Kentucky': self.usapath / 'Kentucky',
                'Louisiana': self.usapath / 'Louisiana',
                'Massachusetts': self.usapath / 'Massachusetts',
                'Maryland': self.usapath / 'Maryland',
                'Maine': self.usapath / 'Maine',
                'MarshallIslands': self.usapath / 'MarshallIslands',
                'Michigan': self.usapath / 'Michigan',
                'Minnesota': self.usapath / 'Minnesota',
                'Missouri': self.usapath / 'Missouri',
                'Mississippi': self.usapath / 'Mississippi',
                'Montana': self.usapath / 'Montana',
                'NorthCarolina': self.usapath / 'NorthCarolina',
                'NorthDakota': self.usapath / 'NorthDakota',
                'NorthernMarianaIslands': self.usapath / 'NorthernMarianaIslands',
                'Nebraska': self.usapath / 'Nebraska',
                'NewHampshire': self.usapath / 'NewHampshire',
                'NewJersey': self.usapath / 'NewJersey',
                'NewMexico': self.usapath / 'NewMexico',
                'Nevada': self.usapath / 'Nevada',
                'NewYork': self.usapath / 'NewYork',
                'Ohio': self.usapath / 'Ohio',
                'Oklahoma': self.usapath / 'Oklahoma',
                'Oregon': self.usapath / 'Oregon',
                'Pennsylvania': self.usapath / 'Pennsylvania',
                'PuertoRico': self.usapath / 'PuertoRico',
                'Palau': self.usapath / 'Palau',
                'RhodeIsland': self.usapath / 'RhodeIsland',
                'SouthCarolina': self.usapath / 'SouthCarolina',
                'SouthDakota': self.usapath / 'SouthDakota',
                'Tennessee': self.usapath / 'Tennessee',
                'Texas': self.usapath / 'Texas',
                'Utah': self.usapath / 'Utah',
                'Virginia': self.usapath / 'Virginia',
                'VirginIslands': self.usapath / 'VirginIslands',
                'Vermont': self.usapath / 'Vermont',
                'Washington': self.usapath / 'Washington',
                'Wisconsin': self.usapath / 'Wisconsin',
                'WestVirginia': self.usapath / 'WestVirginia',
                'Wyoming': self.usapath / 'Wyoming'
            }
        }
        self.create_all_directories(self.Countries)

        self.geodatabase = self.dbpath / 'GeoDatabase.db'
        
        self.Idaho_Boise_html = self.Countries['USA']['Idaho'] / 'Boise' \
            / 'https:_www.accessidaho.org_public_sos_corp_search.html'

        self.codepath = self.rawdatapath / 'Codes'
        self.codepath.mkdir(exist_ok=True)

        self.usapath = self.Countries['USA']

        self.us_business_infopath = self.rawdatapath / 'US-BusinessInfo'
        self.us_business_infopath.mkdir(exist_ok=True)

        self.us_business_info_states_html = self.us_business_infopath / 'html'
        self.us_business_info_states_html.mkdir(exist_ok=True)

        self.us_business_info_url = 'http://us-business.info/directory/'

        self.native_american = self.codepath / 'AIAlist.txt'
        self.national_names = self.codepath / 'NationalFileDomesticNames.txt'
        self.county = self.codepath / 'RawCountyData.txt'
        self.county_sub = self.codepath / 'RawCountySub.txt'
        self.places = self.codepath / 'national_places.txt'
        self.state_cd = self.codepath / 'national_state_codes.txt'
        self.school_districts = self.codepath / 'national_schdist.txt'
        self.voting_districts = self.codepath / 'national_vtd.txt'
        self.congressional_districts = self.codepath / 'national_cd115.csv'

        self.native_american_json = self.jsonpath / 'NativeAmericanAreas.json'
        self.national_names_json = self.jsonpath / 'NationalFileDomesticNames.json'
        self.county_json = self.jsonpath / 'County.json'
        self.county_sub_json = self.jsonpath / 'CountySub.json'
        self.place_json = self.jsonpath / 'Place.json'
        self.state_json = self.jsonpath / 'State.json'
        self.school_districts_json = self.jsonpath / 'SchoolDistricts.json'
        self.voting_districts_json = self.jsonpath / 'VotingDistricts.json'
        self.congressional_districts_json = self.jsonpath / 'CongressionalDistricts.json'

        self.create_all_directories(self.Countries)

    def get_us_business_city_url(self, state):
        """
        state is 2 character abbreviation
        """
        filename = self.us_business_info_states_html / f'{state}_state.html'
        url = f'{self.us_business_info_url}/{state}'
        return filename, url

    def get_us_business_state_city_url(self, city, state):
        """
        city is full city name all lowercase
        state is 2 character abbreviation
        """
        return f'{self.us_business_info_url}/{city}-{state}'

    def get_dir_contents(self, path):
        if isinstance(path, Path) and path.exists():
            return [entry for entry in path.iterdir()]
        return None

    def create_all_directories(self, path):
        for key, value in path.items():
            if isinstance(value, dict):
                self.create_all_directories(value)
            elif isinstance(value, Path) and not value.is_file():
                value.mkdir(exist_ok=True)


def testit():
    bp = BizPaths()
    Scottsdale = bp.usapath['Arizona'] / 'Scottsdale'

    files = bp.get_dir_contents(Scottsdale)

    if files is not None:
        for file in files:
            print(f'{file}')
    else:
        print('Scottsdale directory is empty')


if __name__ == '__main__':
    testit()
Reply
#7
@wavic, looks like new path does not contain dir_2 component, so instead of moving to your designated folder, you are moving it to the current folder. The fault is with the provided path - not with pathlib.rename

That worked - sorry, no fancy pics Wink . I moved a file from a folder test1 to a folder test2

Output:
In [59]: source = pathlib.Path('playground/test1/param.sh') In [60]: source.exists() Out[60]: True In [61]: source.rename('playground/test2/param.sh') In [62]: os.listdir('playground/test1') Out[62]: [] In [63]: os.listdir('playground/test2') Out[63]: ['param.sh']
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#8
Hm! So the rename method doesn't count the path to the file and I have to provide it on my own? Good! That will solve the issue
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why wont this path work one way, but will the other way? cubangt 2 623 Sep-01-2023, 04:14 PM
Last Post: cubangt
  Why doesn't this code work? What is wrong with path? Melcu54 7 1,680 Jan-29-2023, 06:24 PM
Last Post: Melcu54
  Pathlib import not working chriswrcg 9 3,519 May-29-2022, 07:37 PM
Last Post: snippsat
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,149 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  deleting an empty Dir, using pathlib.Path tester_V 9 5,671 Jul-01-2021, 01:53 PM
Last Post: Gribouillis
  Trying to pathlib instead of os.path tester_V 4 2,429 Jun-22-2021, 04:15 AM
Last Post: tester_V
  pathlib destpath.exists() true even file does not exist NaN 9 4,564 Dec-01-2020, 12:43 PM
Last Post: NaN
  Question about if with () or without () / pathlib Tecuma 3 2,157 Apr-02-2020, 10:02 AM
Last Post: Tecuma
  pathlib hanging bluefrog 2 3,089 Sep-25-2018, 12:59 PM
Last Post: volcano63
  pathlib: resolving a path that does not exist Skaperen 6 5,386 Sep-08-2018, 12:25 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020