Can't change txt file name in python

Question:

I need to rename some TXT files with the contents of the first line of the file, but when I run the code below, I get the following error:

"PermissionError: [WinError 32]The process cannot access the file because it is being used by another process"

import os
from datetime import date, time, datetime, timedelta

id = 4577809
data_hoje = date.today().strftime('%Y%m%d')
data = date.today().strftime('%d%m%Y')

caminho_remuneracao = os.listdir(f"C:\Users\{id}\OneDrive\Onedrive - GPA")

for arquivo in caminho_remuneracao:
    if 'GPARH_0030' in arquivo:
        if data in arquivo:
            with open(arquivo, "a+") as arq:
                linhas = arq.readline()
                linha = (linhas[5:19])
                nome = f'GPA_PEDD_{linha}_{data}'
                os.rename(arquivo, nome)
                print(f'arquivo {arquivo} renomeado para {nome}')aminho_remuneracao = os.listdir(f"C:\Users\{id}\OneDrive\Onedrive - GPA")
Asked By: FireWolfBR

||

Answers:

When you call os.rename(), you are calling it within your with open() loop.
You cannot rename the file because the with open() loop is currently using it; try moving the os.rename() outside of this loop.

Try the following:

for arquivo in caminho_remuneracao:
    if 'GPARH_0030' in arquivo:
        if data in arquivo:
            nome=""
            with open(arquivo, "a+") as arq:
                linhas = arq.readline()
                linha = (linhas[5:19])
                nome = f'GPA_PEDD_{linha}_{data}'
            os.rename(arquivo, nome)
            print(f'arquivo {arquivo} renomeado para {nome}')
Answered By: emirps

You have to rename it outside the with block. Try this:

import os
from datetime import date, time, datetime, timedelta

id = 4577809
data_hoje = date.today().strftime('%Y%m%d')
data = date.today().strftime('%d%m%Y')

caminho_remuneracao = os.listdir(f"C:\Users\{id}\OneDrive\Onedrive - GPA")


for arquivo in caminho_remuneracao:
    if 'GPARH_0030' in arquivo:
        if data in arquivo:
            with open(arquivo, "a+") as arq:
                linhas = arq.readline()
                linha = (linhas[5:19])
                nome = f'GPA_PEDD_{linha}_{data}'
            os.rename(arquivo, nome)
            print(f'arquivo {arquivo} renomeado para {nome}')
Answered By: Numan Ijaz

with is your problem

for arquivo in caminho_remuneracao:
    if 'GPARH_0030' in arquivo:
        if data in arquivo:
            arq=open(arquivo, "a+")
            linhas = arq.readline()
            arq.close()
            nome = f'GPA_PEDD_{linhas[5:19]}_{data}'
            os.rename(arquivo, nome)
            print(f'arquivo {arquivo} 

Answered By: geekay
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.