how to delete all lines after a certain string in a file and then add some more lines using python

时间:2016-04-07 10:47:07

标签: python linux append

I want to delete all the lines in a file smart.txt and then add some strings of my own. smart.txt contains alot of lines.

I tried

import sys
import os

output=[]
f= open(smart.txt, 'r')
for line in f:
 output.append(line)
 if '*** P R O P E R T I E S ***' in line: break
f=open(smart.txt, 'w')
[f.write(data) for data in output]
f.write('*** Inclusions ***\n ')
f.write('*** Permanent  ***\n ')
f.close()

I am getting an error

f= open(smart.txt, 'r')
NameError: name 'smart' is not defined

cannot figure out because smart.txt is present in the same directory.

Any suggestions?

1 个答案:

答案 0 :(得分:1)

You need to use 'smart.txt' instead of smart.txt when you're opening the file. So you would change f= open(smart.txt, 'r') to f= open('smart.txt', 'r').

Also you should use with open('smart.txt', 'r') as f to automatically close the file when you are done with it.

Tutorial on file io: link