0
with open("textfile.txt", 'r+') as fin: 
    text = fin.read()

    fin.write(text.replace(" full stop ","."))
    fin.write(text.replace("New Paragraph","\n \t"))

I want to add punctuation in the file. e.g. replace the words "Full Stop" with the actual punctuation mark "." and "New Paragraph" with " \n\t ". The code is not giving any error but it is not replacing any string

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Kapil Gund
  • 19
  • 2

1 Answers1

0

Actually i see you open the file with r+ which will create a new file if it does not exist, and if it will create it will have no content and then it will raise error.

Better is you check first is the file is empty with

import os
if os.stat("filename.txt").st_size == 0:
  # ADD SOME CODE HERE TO ADD CONTENT TO FILE

And then add content

Wasif
  • 14,755
  • 3
  • 14
  • 34