Python string replace in a file without touching the file if no substitution was made

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?

Using Python, I'm trying to replace occurrences of 'oldtext' with 'newtext' in a set of files. If a file contains 'oldtext', I want to do the replacement and save the file. Otherwise, do nothing, so the file maintains its old timestamp.

The following code works fine, except all files get written, even if no string substitution was made, and all files have a new timestamp.

for match in all_files('*.html', '.'):  # all_files returns all html files in current directory     
  thefile = open(match)
  content = thefile.read()              # read entire file into memory
  thefile.close()
  thefile = open(match, 'w')             
  thefile.write(content.replace(oldtext, newtext))  # write the file with the text substitution
  thefile.close()

In this code I'm trying to do the file.write only if a string substitution occurred, but still, all the files get a new timestamp:

count = 0
for match in all_files('*.html', '.'):       # all_files returns all html files in current directory
    thefile = open(match)
    content = thefile.read()                 # read entire file into memory
    thefile.close()
    thefile = open(match, 'w')
    replacedText = content.replace(oldtext, newtext) 
    if replacedText != '':
        count += 1
        thefile.write(replacedText)
    thefile.close()
print (count)        # print the number of files that we modified

At the end, count is the total number of files, not the number of files modified. Any suggestions? Thanks.

I'm using Python 3.1.2 on Windows.

5
задан LandedGently 12 March 2011 в 23:02
поделиться