Search code examples
pythonpython-3.xfiledirectory

Changing name of the file to parent folder name


I have a bunch of folders in my directory. In each of them there is a file, which you can see below:

enter image description here

Regardless the file extension I would like to have the name of this file to be exactly the same as its parent folder, i.e. when considering folder 2023-10-18 I would like to have the file inside 2023-10-18 instead of occultation....

I tried to rename the multiple files by using this thread:

Renaming multiple files in a directory using Python

and here

https://pynative.com/python-rename-file/#:~:text=Use%20rename()%20method%20of,function%20to%20rename%20a%20file.

but unfortunately after application the code like this:

 import os
 from pathlib import Path
 pth = Path(__file__).parent.absolute()
 files = os.listdir(pth)

 for file in files:
 os.rename(os.pth.join(pth, file), os.pth.join(pth, '' + file + '.kml'))

I have an error:

AttributeError: module 'os' has no attribute 'pth'

described here:

AttributeError: 'module' object has no attribute

which says only a little to me, as I am a novice in Python.

How can I auto change the name of all the files in these directories? I need the same filename as the directory name. Is it possible?

UPDATE:

After hint below, my code looks like this now:

 import os
 from pathlib import Path
 pth = Path(__file__).parent.absolute()
 files = os.listdir(pth)

 for file in files:
  os.rename(os.path.join(pth, file), os.path.join(pth, '' + file + '.kml'))

but instead of changing the filename inside the folder list, all the files in the given directory have been changed to .kml. How can I access to the individual files inside the folderlist?

enter image description here


Solution

  • So, based on what I understood, you have a single file in each folder. You would like to rename the file with the same folder name and preserve the extension.

    import os
    
    # Passing the path to your parent folders
    path = r'D:\bat4'
    
    # Getting a list of folders with date names
    folders = os.listdir(path)
    
    for folder in folders:
        files = os.listdir(r'{}\{}'.format(path, folder))
    
        # Accessing files inside each folder
        for file in files:
    
            # Getting the file extension
            extension_pos = file.rfind(".")
            extension = file[extension_pos:]
    
            # Renaming your file
            os.rename(r'{}\{}\{}'.format(path, folder, file),
                      r'{}\{}\{}{}'.format(path, folder, folder, extension))
    

    I have tried it on my own files as follows:

    enter image description here

    enter image description here

    This is an example for the output:

    enter image description here

    I hope I got your point. :)