0

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
2
  • 3
    You need to account for the spaces. "ALS"+str(4277) is the same as "ALS4277" Commented Oct 20, 2016 at 9:20
  • This space is different for different input files. Commented Oct 20, 2016 at 9:24

3 Answers 3

2

Using the same idea that other user have already pointed out, you could also reproduce the same spacing, by first matching the spacing and saving it in a variable (spacing in my code):

import re

with open('input.txt') as f:
    lines = f.read()

match = re.match(r'ALS(\s+)4277', lines)
if match != None:
    spacing = match.group(1)
    lines = re.sub(r'ALS\s+4277', 'KLM%s4945'%spacing, lines.rstrip())

print lines
Sign up to request clarification or add additional context in comments.

3 Comments

I thought about doing this: spaces = " " * 14 then "KLM%s4945" % spaces to make the spaces consistent.
Ha, I swear this question has changed since I answered it.
Don't know about the question being changed - I really don't remember whether the OP stated that she/he wanted to keep the spaces or not. I just thought the spaces might vary, so maybe it would be easier to "automatize" the task :)
1

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())

print(line)

Comments

0

Try:

with open('input.txt') as f:
    for line in f:
        a, b = line.strip().split()
        if a == 'ALS' and b == '4277':
            line = line.replace(a, 'KLM').replace(b, '4945')
        print(line, end='') # as line has '\n'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.