|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
新人报道,
同时有个问题想问下各位
我想用python对文件中的部分字段进行替换,然后保存在同一个文件中,
def substitute_file(file,keyword,replacement):
if not os.path.exists(file): #check whether or not the file exists
print('the file does not exist')
exit(-1)
file_handler=open(file,'r')
contents=file_handler.read() #store the contents temporarily
file_handler.close()
contents=contents.replace(keyword,replacement) #substitute
newfile=open(file,'w') #write back to the same file
newfile.write(contents)
newfile.close()
这是我现在写的,读取整个文件,然后替换部分关键字,再打开同一个文件,open( ,'w')相当于清空重新写。
这样做感觉很傻 对于比较小的文件,还可以,如果是比较大的文件,读取整个文件的开销就很大,但是如果用readlines(),不太明白怎么能马上将替换的字段写回到原文中
感谢各位。。
新人请不要见笑。。。
|
|