在python中将相同的文本附加到文件的每一行

时间:2017-11-07 06:25:49

标签: python

我有一个这种模式的文件:

    Y2.249 Z283.923 A3=-1.0 B3=0.0 C3=0.0 
    Y2.758 Z283.731 A3=-1.0 B3=0.0 C3=0.0

我需要在文件的每一行之前附加字符GOTO /。我怎么做?这是我的代码

def main():
     file=open("orig.txt","r")
     lines=file.readlines()
     file.close()
     for line in lines:
     line=line.strip()
     print(line)
main()

2 个答案:

答案 0 :(得分:0)

试试这个:

def main():
     with open("orig.txt","r") as in_file:
         lines=in_file.readlines()

     out_lines = ["GOTO/{}\n".format(line.strip()) for line in lines]

     with open("new.txt", "w") as out_file:
         out_file.writelines(out_lines)

main()

您可以在new.txt

中找到修改后的内容

答案 1 :(得分:0)

这可能对您有所帮助

Insert string at the beginning of each line

 with open('data.txt', 'r') as f:
        lines = f.readlines()
    lines = ['GOTO '+line for line in lines]
    with open('data.txt', 'w') as f:
        f.writelines(lines)