0

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.

mdpoleto
  • 711
  • 2
  • 6
  • 10
  • Depending on what you are after, perhaps this is a duplicate of [this SO post](http://stackoverflow.com/questions/1325905/inserting-line-at-specified-position-of-a-text-file-in-python/1325927#1325927) – zehnpaard Mar 13 '15 at 05:11

3 Answers3

1

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)
KevB
  • 304
  • 1
  • 7
1

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
zehnpaard
  • 6,003
  • 2
  • 25
  • 40
  • Nice! It worked. But in that case, it would run all lines, change the ones that I need and print unchanged lines as well. Wouldn't this be memory costly? – mdpoleto Mar 13 '15 at 13:04
  • Based on the docs, it appears that in fact `fileinput` is not memory inefficient. You don't load a copy of the entire file in memory, instead the buffer copy is actually made in harddisk, and accessed line by line. So it may be harddisk inefficient, but that's probably how every other text editor implements it as well. And harddisk space is usually not the key constraint. – zehnpaard Mar 13 '15 at 14:54
0

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

David Zemens
  • 53,033
  • 11
  • 81
  • 130