Home > OS >  Losing absolute paths after returning them from function
Losing absolute paths after returning them from function

Time:12-31

I have this function here that renames (if necessary) all files in a given folder and returns all filenames as absolute paths:

import re
import os

# This function renames all files in a given
# folder and return them as absolute paths
def rename_get_Files(filepath):
    files = os.listdir(filepath)
    files_list = []
    counter = 1
    files_renamed = 0
    for filename in files:
        # If the file does not start with 'Offer_Pic_' > rename it and add to the files_list
        if not re.search('Offer_Pic_. ', filename):
            file_name, file_extension = os.path.splitext(filepath filename)
            print(file_extension)

            new_filename = "Offer_Pic_"   str(counter)   file_extension
            old_filename = filepath   filename
            new_filename = filepath   new_filename
            # rename() function will
            # rename all the files
            os.rename(old_filename, new_filename)
            counter  = 1
            print(f'This is the new filename: '   new_filename)
            files_list.append(new_filename)
            files_renamed  = 1
        else:
            # Append the absolute paths of all already correctly named files to the files_list
            files_list.append(os.path.abspath(filename))
    print(files_list)
    print(f'We have renamed '   str(files_renamed)   ' files.')
    return files_list

However, when I call the function from another one to use these absolute paths:

pictures = rename_get_Files(filepath)
print(pictures)

... it returns the paths being inside the script's working directory.

Because of that, the next function of my script crashes because it assumes that the files are in the working directory of the script - which they are not as they were not moved from their initial location (filepath).

Please help me to keep the absolute file paths.

I tried to regain the absolute path of the pictures, but the wrong one (inside script dir keeps being returned)

for pic in pictures:
    abs_path_pic = os.path.abspath(pic)
    print(pic)
    print(abs_path_pic)
    pictureBox.send_keys(abs_path_pic)

CodePudding user response:

when you call the function:

rename_get_Files(filepath)

add a path separator / at the end of filepath, if there's none. For example:

rename_get_Files(filepath   "/")

CodePudding user response:

You can make your function much more readable and easier to maintain with pathlib:

from pathlib import Path


def rename_files(folder, prefix='Offer_Pic_'):
    files = []
    counter = 0

    for old in Path(folder).glob('*'):
        if old.is_file():
            if old.name.startswith(prefix):
                files.append(old)
                continue  

            counter  = 1

            new = old.with_name(f'{prefix}{counter}{old.name}')
            old.rename(new)
            files.append(new)
        
            print(f'Renamed {old} to {new}')

    return files, counter


files, counter = rename_files('/some/path/to/files')

print(*files, sep='\n')
print(f'{counter} files renamed.')

The code above with returns a list of Path objects, which are easier for you to work with.

Bear in mind that the code above is just a starting point. It lacks things like testing if new_name file already exists, for example.

  • Related