鱼C论坛

 找回密码
 立即注册
查看: 2436|回复: 2

新人求解 如何对文件中的字段进行替换

[复制链接]
发表于 2015-8-19 11:20:03 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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(),不太明白怎么能马上将替换的字段写回到原文中

感谢各位。。
新人请不要见笑。。。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2015-8-25 01:16:53 | 显示全部楼层
Python 自己带着电池:

  1. import fileinput

  2. for line in fileinput.input("文件名", inplace=True):
  3.     print(line.replace("被替换的内容", "替换的内容"), end='')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-8-24 10:47:25 | 显示全部楼层
坐等大神回复,我也想学习!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-17 07:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表