Lan*_*tly 5 python file-io replace
如果没有进行字符串替换,Python的string.replace会返回什么?即使没有进行任何更改,Python的file.open(f,'w')是否始终触摸该文件?
使用Python,我试图在一组文件中用'newtext'替换'oldtext'的出现.如果文件包含'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()
Run Code Online (Sandbox Code Playgroud)
在这段代码中,我只是在发生字符串替换时尝试执行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
Run Code Online (Sandbox Code Playgroud)
最后,count是文件总数,而不是修改的文件数.有什么建议?谢谢.
我在Windows上使用Python 3.1.2.
unu*_*tbu 14
如果没有进行字符串替换,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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4712 次 |
| 最近记录: |