尝试使用Python在文本文件中的特定位置添加文本

In the second function I'm attempting to add "TEST: " right before a specific line in the text file. Note the second line where I'm trying to include the backslashes. I've tried putting 4 backslashes for each backslash, but that did not work. Here's the: code

import fileinput as fi
import re


def setup():
    input_file = r"C:\Users\Phillipos Admasu\Documents\India\india_work.txt"
    intermediate_file = r"C:\Users\Phillipos Admasu\Documents\India\india_work_inter.txt"

    with open(input_file) as og:
        with open(intermediate_file, 'w+') as inter:
            for line in og:
                inter.write(re.sub('\s', '\n', line))  # This makes a line break after every Data unit.

def edits():
    intermediate_file = r"C:\Users\Phillipos Admasu\Documents\India\india_work_inter.txt"
    output_final = r'C:\Users\Phillipos Admasu\Documents\India\india_work_final.txt'

    with open(intermediate_file) as inter:
        with open(output_final, 'w') as out_final:
            # for line in inter:
            #     out_final.write(re.sub(r'\n','\n',line))

            for line in fi.FileInput(inter, inplace=1):
                if '\\qc208' in line:
                    line = line.replace(line,"TEST: " + line)
                    print(line, end='')



if __name__ == "__main__":
    setup()
    edits()
评论