Zach Gates
Zach Gates

Reputation: 283

Why won't this code replace this text?

I have this code:

count = -1
with open("text.txt", "r") as f:
    content = f.readlines()
for line in content:
    if line.startswith("  <Vertex>"):
        count += 1
        line = line.replace(str(line), str("  <Vertex> " + str(count) + " {\n"))
        continue
    else:
        pass
with open("text2.txt", "w") as f:
    f.writelines(content)

When it runs, it should replace any line that starts with " <Vertex>" with " <Vertex> 0 {", or whatever number the count is on.

When I run it, it executes fine, but when I open the new text2.txt file, it is the exact same as text.txt.

What am I doing wrong?

Upvotes: 0

Views: 93

Answers (1)

Michael Aquilina
Michael Aquilina

Reputation: 5540

You are not writing back to line, but rather assigning the variable line a new string reference. You need to write back to the contents array as follows instead:

count = -1
with open('text.txt', 'r') as f:
    content = f.readlines()

for index, line in enumerate(content):
    if line.startswith('  <Vertex>'):
        count += 1
        content[index] = line.replace(str(line), str("  <Vertex> " + str(count) + " {\n"))

with open('text2.txt', 'w') as f:
    f.writelines(content)

See if that works for you

You might also want to consider improving your logic as this will only work on very specific patterns.

For example you can replace line.startswith(" <Vertex>") with line.contains('<Vertex>') as this should give you the same results assuming your working with XML

EDIT: There are a number of other things you can do to improve your code but I dont want to bombard you with information. See the suggestion of the commenter below for how to make it more optimised (although I assume at the scale your working it wont make a difference)

Upvotes: 3

Related Questions