简体   繁体   中英

Replacing one string with another for a set of text files using python file.readlines() and .replace() not saving replacement

I have tried to iterate line by line through the text file to find the sections I'm looking to replace and update them with the desired values. The problem I have is that I seem to be updating the value but the value is not written in to the the string. I have printed the output from the file as an explanation of sorts.

for files in glob.iglob(directory+'*'+suffix, recursive=True):
    if "-pst" not in files and "Static" not in files:
        print(files)
        file1 = open(files,"r")
        data=file1.readlines()
        for line in data:
            if "6168" in line:
                print(line)
                line=line.replace("6168", GuideNodes[0])
                print(line)
            line=line.replace("6158", GuideNodes[1])
        
        for line in data:
            if "6168" in line:
                print(line+"$")

The output for this code is:

 6168, 1

 6170, 1

 6168, 4

 6170, 4

 6168, 2

 6170, 2

 6168, 3

 6170, 3

 6168, 5

 6170, 5

 6168, 6

 6170, 6

 6168, 1
$
 6168, 4
$
 6168, 2
$
 6168, 3
$
 6168, 5
$
 6168, 6
$

So you can see that the code initially updates the line but this is not carried over into "data".

I'm working line by line as I also need to move some lines in the code as the text file is a script for another application otherwise I would just edit the text as one long string using file.read().

I'd greatly appreciate if anyone can explain why this is not working as I'd expect!

Strings in Python are immutable, so when you write line=line.replace("6168", GuideNodes[0]) , you create a new string and assign it to line , but it does not change the original value on your data list.

To update the contents of the list, you should change your inner loop to:

for idx, line in enumerate(data):
    if "6168" in line:
        print(line)
        line=line.replace("6168", GuideNodes[0])
        print(line)
    line=line.replace("6158", GuideNodes[1])
    data[idx] = line   # Replaces the original line in data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM