代码之家  ›  专栏  ›  技术社区  ›  mdpoleto

将文本插入行尾python

  •  0
  • mdpoleto  · 技术社区  · 10 年前

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

    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)
    

    我是蟒蛇的新手。你能帮忙吗?

    编辑:我在(很棒的)建议之后更新了我的脚本,但它仍然没有改变我的台词。

    3 回复  |  直到 10 年前
        1
  •  1
  •   zehnpaard    10 年前

    如果要修改文本文件,而不是将一些文本附加到内存中的python字符串中,可以使用 fileinput 标准库中的模块。

    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
    
        2
  •  1
  •   KevB    10 年前

    大部分都是正确的,但正如您所注意到的,字符串没有附加函数。在前面的代码中,您使用+运算符组合了字符串。你可以在这里做同样的事情。

    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)
    
        3
  •  0
  •   David Zemens    10 年前

    这将进行字符串连接:

    line += str(MD)
    

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

    加法与赋值运算符,它将右操作数与左操作数相加,并将结果分配给左操作数