简体   繁体   中英

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.

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM