-2

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?

Hamad Hassan
  • 139
  • 3
  • 13

1 Answers1

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

Farhan.K
  • 3,425
  • 2
  • 15
  • 26