python replace如果没有替换成功_如果没有进行替换,Python字符串会替换文件而不触及文件...

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.

解决方案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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值