erhan erhan - 1 year ago 96
Python Question

how to replace a line of two words in a file using python

I want to replace a line in a file but my code doesn't do what I want. The code doesn't change that line. It seems that the problem is the space between ALS and 4277 characters in the input.txt. I need to keep that space in the file. How can I fix my code?

A part part of input.txt:

ALS 4277

Related part of the code:

for lines in fileinput.input('input.txt', inplace=True):
print(lines.rstrip().replace("ALS"+str(4277), "KLM" + str(4945)))

Desired output:

KLM 4945

Answer Source

As the spaces vary you will need to use regex to account for the spaces.

import re

lines = "ALS              4277    "
line = re.sub(r"(ALS\s+4277)", "KLM              4945", lines.rstrip())

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download