2014-11-06 426 views
0

我知道这里存在很多关于使用python 2查找和替换文件中的文本的问题。然而,作为python的一个非常新的东西,我不理解语法并可能是目的也会有所不同。Python 2.x查找并替换多行文本

我在寻找的东西非常简单的代码行作为在Linux shell脚本

sed -i 's/find/replace/' *.txt 
sed -i 's/find2/replace2/' *.txt 

可以此代码的工作,以取代多行文本

with open('file.txt', 'w') as out_file: 
    out_file.write(replace_all('old text 1', 'new text 1')) 
    out_file.write(replace_all('old text 2', 'new text 2')) 

而且,似乎有越来越另一换行符问题,我不想要。任何想法或帮助?

+0

@ inspectorG4dget我想使用同一个文件。没有不同的读写文件 – gyeox29ns 2014-11-06 02:37:33

+0

这就是你需要的:http://stackoverflow.com/questions/5453267/is-it-possible-to-modify-lines-in-a-file-in-place – user3885927 2014-11-06 04:59:51

回答

2

因此,使用Python,最简单的方法是将文件中的所有文本读取到字符串中。然后使用该字符串执行任何必要的替换。然后写了整个事情回来了同一个文件:

filename = 'test.txt' 

with open(filename, 'r') as f: 
    text = f.read() 

text = text.replace('Hello', 'Goodbye') 
text = text.replace('name', 'nom') 

with open(filename, 'w') as f: 
    f.write(text) 

replace方法适用于任何字符串替换第二个是第一个参数的任何(区分大小写)匹配。您只需通过两个不同的步骤即可阅读和写入同一个文件。

2

下面是一个快速示例。如果你想更强大的查找/替换你可以使用正则表达式,而不是与string.replace

import fileinput 
for line in fileinput.input(inplace=True): 
    newline = line.replace('old text','new text').strip() 
    print newline 

把上面的代码中所需的文件,说sample.py,并假设您的蟒蛇在您的路径,你可以为运行:

python sample.py inputfile 

这将在输入文件中用'新文本'替换'旧文本'。当然你也可以传递多个文件作为参数。请参阅https://docs.python.org/2/library/fileinput.html

+0

如果我想要替换2个不同的文本实例,那么这是正确的? 'newline = line.replace('old text 1','new text 1')。strip() newline = line.replace('old text 2','new text 2')。strip写了2行文本替换命令。 – gyeox29ns 2014-11-06 18:55:12

+0

string.replace将会替换所有的实例。如果你想限制有多少实例被替换,你可以指定另一个带有实例数量的参数来替换。看到https://docs.python.org/2/library/string.html在最底层 – user3885927 2014-11-06 18:58:01

+0

我想我不清楚我想传达什么。我并不是说要替换_n_实例,而是说替换两个或更多不同的文本行(正如我在'sed'命令中所显示的那样。你引用的链接可以限制替换文本的次数。 – gyeox29ns 2014-11-06 19:02:17