Python的string.replace在没有字符串替换时返回什么?
如果没有进行更改,Python的file.open(f, 'w')是否总是会触碰到文件?
我正在使用Python尝试替换一组文件中的'oldtext'出现次数为'newtext'。如果文件包含'oldtext',则要进行替换并保存文件。否则,不执行任何操作,以便文件保留其旧时间戳。
以下代码运行良好,但是即使没有进行字符串替换,所有文件也会被写入,并且所有文件都具有新的时间戳。
在这段代码中,我试图只在发生字符串替换时进行文件写入,但是所有文件仍然会获得新的时间戳:
我正在使用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()
在这段代码中,我试图只在发生字符串替换时进行文件写入,但是所有文件仍然会获得新的时间戳:
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。
oldtext
对象所持有的字符串替换所有出现的该字符串,用名为newtext
对象所持有的字符串替换它?如果是前者,有一种很简单的方法可以做到。 - eyquem