在行尾插入文本python

2024-04-25 12:23:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在循环中的文本文件中的特定行的末尾追加一些文本。 到目前为止,我有以下情况:

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)

我是python的新手。你能帮忙吗?在

编辑:我更新了我的脚本后(伟大的)建议,但它仍然没有改变我的行。在


Tags: in文本forosbatchline情况templ
3条回答

这将执行字符串连接:

line += str(MD)

这里有一些more documentation on the operators,因为python支持赋值运算符。a += b相当于:a = a + b。在python中,与其他一些语言一样,+=赋值运算符执行以下操作:

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

大部分都是正确的,但是正如您所指出的,字符串没有append函数。在前面的代码中,您将字符串与+运算符组合在一起。你可以在这里做同样的事情。在

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)

如果您想修改文本文件,而不是向内存中的python字符串追加一些文本,那么可以使用标准库中的^{}模块。在

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

相关问题 更多 >

    热门问题