如果没有进行替换,Python 字符串将在文件中替换,而不触及文件

2023-12-14

如果没有进行字符串替换,Python 的 string.replace 返回什么? 即使没有进行任何更改,Python 的 file.open(f, 'w') 是否始终会触及文件?

使用 Python,我尝试将一组文件中出现的“oldtext”替换为“newtext”。如果文件包含“oldtext”,我想进行替换并保存文件。否则,不执行任何操作,因此文件将保留其旧时间戳。

下面的代码工作正常,除了所有文件都被写入,即使没有进行字符串替换,并且所有文件都有一个新的时间戳。

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()

在这段代码中,我尝试仅在发生字符串替换时执行 file.write ,但所有文件仍然会获得新的时间戳:

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

最后,count 是文件总数,而不是修改的文件数。有什么建议么?谢谢。

我在 Windows 上使用 Python 3.1.2。


Python的string.replace有什么作用 如果没有字符串替换则返回 制成?

它返回原始字符串。

Python 的 file.open(f, 'w') 总是 即使没有发生任何更改,也触摸该文件 制成?

它不仅仅是触及文件,它还会破坏任何内容f用于容纳。

因此,您可以测试文件是否需要重写if replacedText != content,并且仅在这种情况下以写入模式打开文件:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果没有进行替换,Python 字符串将在文件中替换,而不触及文件 的相关文章

随机推荐