mdpoleto
mdpoleto

Reputation: 803

Inserting text to end of line python

I want to append some text to the end of a specific line in a text file, inside a loop. So far, I have the following:

batch = ['1', '2', '3', '4', '5']
list = ['A', 'B', 'C']

for i in list:
    for j in batch:
        os.chdir("/" + i + "/folder_" + j + "/")

        file = "script.txt"
        MD = "TEXT"
        with open(file) as templist:
            templ = templist.read().splitlines()
        for line in templ:
            if line.startswith("YELLOW"):
                line += str(MD)

I am a newbie at python. Could you please help?

EDIT: I've updated my script after (great) suggestions, but it still does not change my line.

Upvotes: 0

Views: 2545

Answers (3)

zehnpaard
zehnpaard

Reputation: 6223

If you want to modify the text file, rather than append some text to a python string in memory, you can use the fileinput module in the standard library.

import fileinput

batch = ['1', '2', '3', '4', '5']
list = ['A', 'B', 'C']

for i in list:
    for j in batch:
        os.chdir("/" + i + "/folder_" + j + "/")

        file_name = "script.txt"
        MD = "TEXT"
        input_file = fileinput.input(file_name, inplace=1)
        for line in input_file:
            if line.startswith("YELLOW"):
                print line.strip() + str(MD)
            else:
                print line,
        input_file.close() # Strange how fileinput doesn't support context managers

Upvotes: 2

David Zemens
David Zemens

Reputation: 53623

This will do string concatenation:

line += str(MD)

Here is some more documentation on the operators, as python supports assignment operators. a += b is equivalent to: a = a + b. In python, as in some other languages, the += assignment operator does:

Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

Upvotes: 0

KevB
KevB

Reputation: 314

You have most of it right, but as you noted strings don't have an append function. In the previous code you combined strings with the + operator. You can do the same thing here.

batch = ['1', '2', '3', '4', '5']
list = ['A', 'B', 'C']

for i in list:
    for j in batch:
        os.chdir("/" + i + "/folder_" + j + "/")

        file = "script.txt"
        MD = "TEXT"
        with open(file) as templist:
            templ = templist.read().splitlines()
        for line in templ:
            if line.startswith("YELLOW"):
                line += str(MD)

Upvotes: 1

Related Questions