1

I was trying to automize file renaming process using the following code in python:

import re
import datetime
path = "C:\\Users\\Public\\filexyz"


for filename in os.listdir(path):

     if filename.endswith('.txt'):
       
        with open(os.path.join(path, filename), 'r') as file:
            content = file.read()

            start_date = re.search(r"LAST\sSTATEMENT\s(\d{2}/\d{2}/\d{2})", content).group(1)

            end_date = re.search(r"THIS\sSTATEMENT\s(\d{2}/\d{2}/\d{2})", content).group(1)

            new_filename = f"{start_date}-{end_date}.txt"

            os.rename(os.path.join(path, filename), os.path.join(path, new_filename))

The error:

os.rename(os.path.join(path, filename), os.path.join(path, new_filename)) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\Public\filexyz\OB1452.txt' -> 'C:\Users\Public\filexzy\09/30/22-10/31/22.txt'

I have searched solutions on statoverflow and tried 'file.close()' but could not resolve the error. The idea is to rename the file using 2 dates in the content (for instance: 09/28/21-10/30/21.txt) Your advice will be much appreciated! Thank you!

Phil C
  • 11
  • 2
  • There is a previous error that does not allow the program to continue... so you should see the previous error text. – Mohsen Hrt Apr 01 '23 at 00:04

0 Answers0