Python搜索文本文件字符串并替换它

嗨,
我正在创建脚本以匹配字符串并替换它
在mount t.txt中
米奇:/工作1/工作1什么都不是
米奇:/work2/work2 bla bla bla
MICKET:/JOB/JOB BLAB BLAB

选择 | 换行 | 行号
  1. #!/usr/bin/python
  2. import string
  3. s = open("/usr2/py/mount.txt","r+")
  4. for line in s.readlines():
  5.    print line
  6.    string.replace(line, 'mickey','minnie')
  7.    print line
  8. s.close()
  9.  

然而,字符串.替换似乎不起作用,有什么建议吗?谢谢!
我使用的是CentOS 4.6,而PYTHON是2.3.4

# 回答1


你好,DannyMc,
字符串.替换()
不原地修改参数字符串,但返回修改后的字符串。你必须做一项任务。除非您的文件非常大,否则我建议您通过读取文件、修改文本并将修改后的文本写回文件来更新文件中的文本。您可以使用字符串方法
替换()
而不是导入字符串模块。

选择 | 换行 | 行号
  1. s = open("mount.txt").read()
  2. s = s.replace('mickey', 'minnie')
  3. f = open("mount.txt", 'w')
  4. f.write(s)
  5. f.close()
# 回答2


谢谢你的解决方案bvdet!
# 回答3


您可以使用文件输入进行就地编辑

选择 | 换行 | 行号
  1. import fileinput
  2. for line in fileinput.FileInput("file", inplace=1):
  3.     line=line.replace("old","new")
  4.     print line
  5.  
# 回答4


大家好,我用以下脚本解决了我的问题:

选择 | 换行 | 行号
  1. #!/usr/bin/python
  2. import re
  3. #fstab location, use w mode as need to overwrite whole file.
  4. s = open("/usr2/py/mount.txt","r")
  5. #temp txt file to store new mount.
  6. tmpfile = open("/usr2/py/tmp.txt","a")
  7. #new nas mount point
  8. newmount = open("/usr2/py/newmount.txt","r")
  9. #search pg-swnas1 line
  10. for line in s.readlines():
  11.     if re.search("filer", line, re.IGNORECASE) != None:
  12.         print line
  13.     else:
  14.         tmpfile.write(line)
  15. #read the latest mount point
  16. readmount = newmount.read()
  17. #append to temp file
  18. tmpfile.write(readmount)
  19. s.close()
  20. tmpfile.close()
  21. tmpfile = open("/usr2/py/tmp.txt","r")
  22. readtmp = tmpfile.read()
  23. s = open("/usr2/py/mount.txt","w")
  24. s.write(readtmp)
  25.  
  26. tmpfile.close()
  27. newmount.close()
  28.  
  29.  

虽然代码可以工作,但它似乎不是一个干净的代码。有什么办法可以简化它吗?

# 回答5


我不太清楚mount t.txt和newmount t.txt包含什么,以及您需要替换什么。你不需要
请注意
。您可以使用
在……里面
接线员。如果我理解正确,这应该是可行的(未经测试):

选择 | 换行 | 行号
  1. mountList = open("/usr2/py/mount.txt", "r").readlines()
  2. newmountList = open("/usr2/py/newmount.txt","r").readlines()
  3. outputList = [item for item in mountList if "filer" not in item.lower()]
  4. outputList.extend(newmountList)
  5. f = open("/usr2/py/mount.txt","w")
  6. f.write(''.join(outputList))
  7. f.close()
# 回答6


效果很好,谢谢!
# 回答7


嗨,bvdet,
该脚本适用于单个文件,但如何才能替换一个目录中的多个文件。
请你写一下剧本好吗?
我的文件扩展名是.xlf
文件夹c:/mrit/
向您致以亲切的问候,
MJ

标签: python

添加新评论