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

后端 未结 3 865
暗喜
暗喜 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:21

    What does Python's string.replace return if no string substitution was made?

    str.replace() returns the string itself or a copy if the object is a subclass of string.

    Does Python's file.open(f, 'w') always touch the file even if no changes were made?

    open(f, 'w') opens and truncates the file f.

    Note the code below is CPython specific; it won't work correctly on pypy, jython:

    count = 0
    for match in all_files('*.html', '.'):
        content = open(match).read()
        replacedText = content.replace(oldtext, newtext) 
        if replacedText is not content:
           count += 1
           open(match, 'w').write(replacedText)
    print (count)   
    

提交回复
热议问题