如果没有进行字符串替换,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。