0

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?

Zach Gates
  • 273
  • 2
  • 5
  • 11
  • related: [How to search and replace text in a file using Python?](http://stackoverflow.com/q/17140886/4279) – jfs Mar 30 '14 at 19:32

1 Answers1

3

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)

Michael Aquilina
  • 5,352
  • 4
  • 33
  • 38
  • 1
    Consider using `range(len(content))` and `content[i]` throughout instead of `enumerate(content)` and `line`, since `enumerate` will create an unnecessary copy of each line. Also, `else:pass` can be safely omitted here, since `else` is always optional. (`try..except` is where `pass` is required when `except` is empty.) – Pi Marillion Mar 30 '14 at 18:51
  • I was considering mentioning these but I did not want to alter the code to much in the hope that it would be more understandable for him. My impression is that OP is probably new to python and I didnt want to bombard him with information – Michael Aquilina Mar 30 '14 at 18:52