Running into issues getting os.rename module to work for automation script

23 Views Asked by At

Im looping through a file with multiple log files that have been assigned a randomized filename. The script should search within the log for the line containing "hostname" and then pull out the assigned hostname to use as the re-assigned file name, which is where im having trouble...total noob....

  import os

path = "/Users/Joel/Desktop/logs"

for file in os.listdir(path):
    with open(f"{path}/{file}") as log:
        for line in log:
            if "hostname" in line:
                desired_filename = line.split()[1].replace('"','')
                os.rename(f'{path}/{file}', f'{path}/{desired_filename}')
                
1

There are 1 best solutions below

6
John Gordon On
for file in os.listdir(path):
    with open(f"{path}/{file}") as file:

Using file as a variable name in the second line replaces the same variable from the first line. You probably want to use different names for these two variables.

        os.rename(file, desired_filename)

You probably need to add path to the front of both of these filenames.