import fileinput
s='''
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
Last line
'''
f=open(r'G:\\13.txt','w')
f.write(s)
f.flush()
f.close()
f=fileinput.input(r'G:\\13.txt',inplace=1,backup='.bak')
for i in f:
if 'fun' in i:
i=i.replace('fun','Fun')
print i,
s='''
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
Last line
'''
f=open(r'G:\\13.txt','w')
f.write(s)
f.flush()
f.close()
f=fileinput.input(r'G:\\13.txt',inplace=1,backup='.bak')
for i in f:
if 'fun' in i:
i=i.replace('fun','Fun')
print i,
f.close()
也可以使用re.sub()对文件进行替换:
f=fileinput.input(r'G:\\13.txt',inplace=1,backup='.bak')
for i in f:
p='fun'
if 'fun' in i:
i=re.sub(p,'FUN',i)
print i,
f.close()

本文介绍如何使用Python读取并修改文本文件中的特定单词,通过两种方法实现将所有出现的'fun'替换为'Fun'或'FUN',一种是简单的字符串替换,另一种则利用正则表达式进行替换。
2000

被折叠的 条评论
为什么被折叠?



