Luis Fernando Silva
Luis Fernando Silva

Reputation: 49

Rename list objects in Python

I have a python code that prints objects that I want to rename to use later

import urllib.request as url

pagina = "https://s3-ifc-coordinador-preprod.s3.amazonaws.com/"
pw = url.urlopen(pagina)
datos = pw.readlines()
print(datos)
for i in datos:
    datos2 = i.decode("utf-8").split("BAEN/")
    for j in datos2:
        if j.count(".xlsx") > 0:
            referencia = j.split("<")
            #new_referencia = referencia.replace('Ago2019', 'May2020')
            #print(new_referencia[0])
            print(referencia[0])

Result:

VE02_FIFC_LUZOSORNO_BAENAgo2019.xlsx
VE02_FIFC_NORVIND_BAENAgo2019.xlsx
VE02_FIFC_POZO_ALMONTE_SOLAR_1_BAENAgo2019.xlsx
VE02_FIFC_SAESA_BAENAgo2019.xlsx
VE02_FIFC_SAFIRA_ENERGIA_CHILE_BAENAgo2019.xlsx
VE02_FIFC_SAN_JUAN_LAP_BAENAgo2019.xlsx
VE02_FIFC_SGA_BAENAgo2019.xlsx
VE02_FIFC_TACORA_ENERGY_BAENAgo2019.xlsx
VE02_FIFC_TRANSELEC_BAENAgo2019.xlsx
VE03_FIFC_AES_GENER_BAENAgo2019.xlsx
VE03_FIFC_CALAMA_SOLAR_1_BAENAgo2019.xlsx
VE03_FIFC_ENGIE_BAENAgo2019.xlsx

I need to change 'Ago2019' to 'May2020'

Clearly using replace(), it doesn't work. Does anyone know how to do it?

Result I require

VE02_FIFC_LUZOSORNO_BAENMay2020.xlsx
VE02_FIFC_NORVIND_BAENMay2020.xlsx
VE02_FIFC_POZO_ALMONTE_SOLAR_1_BAENMay2020.xlsx
VE02_FIFC_SAESA_BAENMay2020.xlsx
VE02_FIFC_SAFIRA_ENERGIA_CHILE_BAENMay2020.xlsx
VE02_FIFC_SAN_JUAN_LAP_BAENMay2020.xlsx
VE02_FIFC_SGA_BAENMay2020.xlsx
VE02_FIFC_TACORA_ENERGY_BAENMay2020.xlsx
VE02_FIFC_TRANSELEC_BAENMay2020.xlsx
VE03_FIFC_AES_GENER_BAENMay2020.xlsx
VE03_FIFC_CALAMA_SOLAR_1_BAENMay2020.xlsx
VE03_FIFC_ENGIE_BAENMay2020.xlsx

Upvotes: 0

Views: 77

Answers (2)

Alterlife
Alterlife

Reputation: 6625

The replace is probably fine, but you haven't replaced it in the array, instead you've assigned it to a new variable that you never use.

Try something like this:

        referencia = j.split("<")
        new_referencia = referencia[0].replace('Ago2019', 'May2020')
        print(new_referencia)

Upvotes: 1

leopardxpreload
leopardxpreload

Reputation: 768

You can use replace on a string:

new_referencia = [i.replace('Ago2019', 'May2020') for i in referencia]
NOTE: split() creates a list

Upvotes: 1

Related Questions