1

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}')
                
Joel Roe
  • 11
  • 2

1 Answers1

1
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.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • `os.rename(path(file), path(desired_filename))` not sure if this is what you mean but it is erroring : 'str' object is not callable – Joel Roe Mar 22 '22 at 01:02
  • That's not what I meant. `file` does not live in the current directory; it lives in the `path` directory. So you have to add `path` to the filename. – John Gordon Mar 22 '22 at 01:09
  • File "c:\Users\Joel\Desktop\python_work\exercises\rename_script.py", line 10, in os.rename(f'{path}/{file}', f'{path}/{desired_filename}') PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: '/Users/Joel/Desktop/logs/file1.txt' -> '/Users/Joel/Desktop/logs/MDF-1234' – Joel Roe Mar 22 '22 at 01:15
  • You're trying to move `file` while you still have it open in the `with open ...` block. – John Gordon Mar 22 '22 at 01:21
  • man...i might be over my head with this lol....so `file.close()` somewhere in the loop? – Joel Roe Mar 22 '22 at 01:33
  • 1
    Edit the question to include your updated code that fixes the first problem in my answer. I have to see that before I can fix this latest issue. – John Gordon Mar 22 '22 at 01:35