简体   繁体   中英

how to add a line above specific lines in python

I have a file kind of like this:

===
1 2 3 4
===
2 3 4 5
===
3 4 5 6

and I am trying to make a program to turn the file into this

p
===
1 2 3 4
p
===
2 3 4 5
p
===
3 4 5 6

Is there any way I could do this in python?

you can use:

with open('my_file.txt') as fp:
    lines = fp.readlines()

for i, l in enumerate(lines):
    if l == '===\n':
        lines[i] = 'p\n===\n'

with open('my_file.txt', 'w') as fp:
    fp.write(''.join(lines))

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