Replace words\characters in text file

1672
10
Jump to solution
07-05-2022 04:01 AM
anTonialcaraz
Occasional Contributor II

Hi, I'm trying to replace some characters within a lyrx file.

In this example I need to replace "570" with "560"

The problem I have is that two lines are identical but I only need to replace one (highlighted in yellow in the image below) and not the one a few lines above the highlighted one.

The code I'm using:

 

for i, line in enumerate(fileinput.input(OUT_workspace + "\\" + "AE000S560_005M5001P01M041.lyrx", inplace=1)):
    sys.stdout.write(line.replace('"max" : 570', '"max" : 560'))

 

I would really appreciate any help. I'm not sure how to target a specific line within the file. Many thanks.

 

Capture.PNG

0 Kudos
10 Replies
Brian_Wilson
Occasional Contributor III

You need to write the changed string back out to a file, you could do this, and avoid loading all those libraries you don't need too. Loading "arcpy" takes forever.

import os

IN_workspace = r"H:\PROGRAMMES\10_OTHER_PROJECTS\26_04072022_KEV"
OUT_workspace = r"H:\PROGRAMMES\10_OTHER_PROJECTS\26_04072022_KEV_NEW"

Lyrx = "AE000S570_005M5001P01M041.lyrx"

with open(os.path.join(IN_workspace, Lyrx), "r") as fp:
    lyrx = fp.read()

fixed = lyrx.replace('570,\n"max"', '560,\n"max"')
if lyrx == fixed:
    print("WARNING, NOTHING CHANGED!")

with open(os.path.join(OUT_workspace, Lyrx), "w") as fp:
    fp.write(fixed)

 

I used "os.path.join" to build up the file paths just because it is tidier, sometimes that avoids problems with missed slashes and stuff like that. It's OS independent too. 

I avoid relying on the arcgis "workspace" because about 1/2 the Esri tools just ignore it.