What does Python\'s string.replace return if no string substitution was made? Does Python\'s file.open(f, \'w\') always touch the file even if no changes were made?
What does Python's string.replace return if no string substitution was made?
It returns the original string.
Does Python's file.open(f, 'w') always touch the file even if no changes were made?
More than merely touching the file, it destroys any content f
used to contain.
So, you can test if the file needs to be rewritten with if replacedText != content
, and only open the file in write mode if this is the case:
count = 0
for match in all_files('*.html', '.'): # all_files returns all html files in current directory
with open(match) as thefile:
content = thefile.read() # read entire file into memory
replacedText = content.replace(oldtext, newtext)
if replacedText!=content:
with open(match, 'w') as thefile:
count += 1
thefile.write(replacedText)
print (count) # print the number of files that we modified