pythonoperating-systemfile-renameshutilpython-os

Python program to rename files doesn't work on files on external drives


I wrote this program to rename all files in a directory to title case, and it works fine on files on the system. But when I use it to rename files on an external drive, the program executes successfully without any exceptions but the filenames remain unchanged.

# Import the os and shutil modules to interact with the operating system and files
import os
import shutil


def main():
    try:
        print("This program will rename all the files in the specified directory to title case.")

        dir_path = input("Enter the directory: ").strip()  # Ask the user to enter the directory path

        if os.path.isdir(dir_path):  # Check if the entered path is a valid directory
            dir_path = os.path.join(dir_path, "")  # Add a trailing slash to the path for later use
        else:
            raise Exception("Invalid path.")  # Raise an exception if it's not a valid directory
        
        for item in os.listdir(dir_path):  # Iterate over all the items in the specified directory
            if os.path.isdir(item):
                continue  # Skip if the item is a directory
            filename, extension = os.path.splitext(item)  # Separate the filename and extension
            filename = filename.title()  # Convert the filename to title case
            destination = os.path.join(dir_path, filename + extension)  # Create path with the new filename
            shutil.move(os.path.join(dir_path, item), destination)  # Rename the file

        print("Operation Successful!")

    except Exception as e:
        print(e)  # If there's an error, print the error message


if __name__ == "__main__":
    main()

I've also tried using the os.rename() function, it didn't work so this is a second try. Also tried running this program in a linux system, didn't work. Asked ChatGPT, it said add os.chdir(dir_path) before the for loop, also didn't work. Help me with it?

UPDATE: As Saxtheowl said in a comment on his answer, the problem with the program not working on external drives was with the file system. My drive was exFAT before, tried changing the file system to NTFS and the program works. Asked ChatGPT about it and it said:

One limitation of exFAT is that it does not support all of the same file operations as NTFS, such as certain types of file permissions and file attributes. This can cause issues when trying to perform certain file operations, such as renaming files or copying files with certain attributes.

In your case, it's possible that the issue with the rename program not working on the exFAT drive was due to the limitations of the file system, such as the maximum file name length or the lack of support for certain file attributes. Changing the file system to NTFS would have allowed the program to work correctly, as NTFS supports a wider range of file operations and has fewer limitations.


Solution

  • Your os.path.isdir(item) fail because item contains only the basename of the file, and the function expects a full path. You should use os.path.join(dir_path, item) instead, here is the modified code:

    import os
    import shutil
    
    def main():
        try:
            print("This program will rename all the files in the specified directory to title case.")
    
            dir_path = input("Enter the directory: ").strip()
    
            if os.path.isdir(dir_path):
                dir_path = os.path.join(dir_path, "")
            else:
                raise Exception("Invalid path.")
    
            for item in os.listdir(dir_path):
                item_path = os.path.join(dir_path, item)  # Create the full path for the item
                if os.path.isdir(item_path):  # Check if the item is a directory using the full path
                    continue
                filename, extension = os.path.splitext(item)
                filename = filename.title()
                destination = os.path.join(dir_path, filename + extension)
                shutil.move(item_path, destination)
    
            print("Operation Successful!")
    
        except Exception as e:
            print(e)
    
    if __name__ == "__main__":
        main()