0

I am trying to edit a text file that is html using python. When printing it, it gives an empty file. Why it gets empty? I tried to print it because I don't know how to return it. Here's the code:

    import bleach 

    with open ('index1.txt','w') as f: #to open the file that contains html markups
    
            bleach.clean( 
             'f',
             tags=['p'],
             attributes=['style'],
             styles=['color'], 
            )    
    
    f=open('index1.txt')
    content = f.read()
    f.close()
    print(content)
Eva
  • 1
  • 1

2 Answers2

1

It becomes empty because you open file for writing with 'w' and thus make it empty as per documentation - just change it to 'r' or 'a'

Drako
  • 773
  • 10
  • 22
0

It would remain empty because you're just creating a file & not writing anything on it.

vikas soni
  • 540
  • 3
  • 9
  • I am trying to edit the file. So how can i do that? in other words, how to return the edited file or print it? – Eva Sep 30 '21 at 07:44
  • If you want to edit the file, open it in append mode like `open("index1.txt", "a")`. If you want to print the file content, open it in read mode like `open("index1.txt", "r")`. – vikas soni Sep 30 '21 at 07:46