嗨,
我正在创建脚本以匹配字符串并替换它
在mount t.txt中
米奇:/工作1/工作1什么都不是
米奇:/work2/work2 bla bla bla
MICKET:/JOB/JOB BLAB BLAB
- #!/usr/bin/python
- import string
- s = open("/usr2/py/mount.txt","r+")
- for line in s.readlines():
- print line
- string.replace(line, 'mickey','minnie')
- print line
- s.close()
-
然而,字符串.替换似乎不起作用,有什么建议吗?谢谢!
我使用的是CentOS 4.6,而PYTHON是2.3.4
# 回答1
你好,DannyMc,
字符串.替换()
不原地修改参数字符串,但返回修改后的字符串。你必须做一项任务。除非您的文件非常大,否则我建议您通过读取文件、修改文本并将修改后的文本写回文件来更新文件中的文本。您可以使用字符串方法
替换()
而不是导入字符串模块。
- s = open("mount.txt").read()
- s = s.replace('mickey', 'minnie')
- f = open("mount.txt", 'w')
- f.write(s)
- f.close()
# 回答3
您可以使用文件输入进行就地编辑
- import fileinput
- for line in fileinput.FileInput("file", inplace=1):
- line=line.replace("old","new")
- print line
-
# 回答4
大家好,我用以下脚本解决了我的问题:
- #!/usr/bin/python
- import re
- #fstab location, use w mode as need to overwrite whole file.
- s = open("/usr2/py/mount.txt","r")
- #temp txt file to store new mount.
- tmpfile = open("/usr2/py/tmp.txt","a")
- #new nas mount point
- newmount = open("/usr2/py/newmount.txt","r")
- #search pg-swnas1 line
- for line in s.readlines():
- if re.search("filer", line, re.IGNORECASE) != None:
- print line
- else:
- tmpfile.write(line)
- #read the latest mount point
- readmount = newmount.read()
- #append to temp file
- tmpfile.write(readmount)
- s.close()
- tmpfile.close()
- tmpfile = open("/usr2/py/tmp.txt","r")
- readtmp = tmpfile.read()
- s = open("/usr2/py/mount.txt","w")
- s.write(readtmp)
-
- tmpfile.close()
- newmount.close()
-
-
虽然代码可以工作,但它似乎不是一个干净的代码。有什么办法可以简化它吗?
# 回答5
我不太清楚mount t.txt和newmount t.txt包含什么,以及您需要替换什么。你不需要
请注意
。您可以使用
在……里面
接线员。如果我理解正确,这应该是可行的(未经测试):
- mountList = open("/usr2/py/mount.txt", "r").readlines()
- newmountList = open("/usr2/py/newmount.txt","r").readlines()
- outputList = [item for item in mountList if "filer" not in item.lower()]
- outputList.extend(newmountList)
- f = open("/usr2/py/mount.txt","w")
- f.write(''.join(outputList))
- f.close()
# 回答7
嗨,bvdet,
该脚本适用于单个文件,但如何才能替换一个目录中的多个文件。
请你写一下剧本好吗?
我的文件扩展名是.xlf
文件夹c:/mrit/
向您致以亲切的问候,
MJ