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

后端 未结 3 838
暗喜
暗喜 2021-01-05 22:56

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?

3条回答
  •  不知归路
    2021-01-05 23:25

    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
    

提交回复
热议问题