在Python中搜索并替换文件中的一行

时间:2008-09-02 09:19:04

标签: python file

我想循环遍历文本文件的内容并在某些行上进行搜索和替换,并将结果写回文件。我可以先将整个文件加载到内存中然后再写回来,但这可能不是最好的方法。

在以下代码中,最好的方法是什么?

f = open(file)
for line in f:
    if line.contains('foo'):
        newline = line.replace('foo', 'bar')
        # how to write this newline back to the file

14 个答案:

答案 0 :(得分:240)

最短的方法可能是使用fileinput module。例如,以下内容为文件添加行号:

import fileinput

for line in fileinput.input("test.txt", inplace=True):
    print "%d: %s" % (fileinput.filelineno(), line),

这里发生的是:

  1. 将原始文件移至备份文件
  2. 标准输出被重定向到循环中的原始文件
  3. 因此,任何print语句都会写回原始文件
  4. fileinput有更多的花里胡哨。例如,它可用于自动操作sys.args[1:]中的所有文件,而无需显式迭代它们。从Python 3.2开始,它还提供了一个方便的上下文管理器,可用于with语句。


    虽然fileinput非常适合一次性脚本,但我会谨慎地在真实代码中使用它,因为不可否认它不是很易读或不熟悉。在实际(生产)代码中,花费更多代码行来使流程显式化并因此使代码可读是值得的。

    有两种选择:

    1. 文件不是太大,你可以把它全部读到内存中。然后关闭文件,以书写模式重新打开文件并重新编写修改后的内容。
    2. 文件太大,无法存储在内存中;您可以将其移动到临时文件并打开它,逐行读取,写回原始文件。请注意,这需要两倍的存储空间。

答案 1 :(得分:168)

我想这样的事情应该这样做。它基本上将内容写入新文件,并用新文件替换旧文件:

from tempfile import mkstemp
from shutil import move
from os import fdopen, remove

def replace(file_path, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    with fdopen(fh,'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                new_file.write(line.replace(pattern, subst))
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)

答案 2 :(得分:71)

这是另一个经过测试的示例,它将匹配搜索&替换模式:

import fileinput
import sys

def replaceAll(file,searchExp,replaceExp):
    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)

使用示例:

replaceAll("/fooBar.txt","Hello\sWorld!$","Goodbye\sWorld.")

答案 3 :(得分:58)

这应该有效:(现场编辑)

import fileinput

# Does a list of files, and
# redirects STDOUT to the file in question
for line in fileinput.input(files, inplace = 1): 
      print line.replace("foo", "bar"),

答案 4 :(得分:22)

根据Thomas Watnedal的回答。 但是,这并没有完全回答原始问题的线到线部分。该功能仍然可以在线到线的基础上替换

此实现在不使用临时文件的情况下替换文件内容,因此文件权限保持不变。

同样re.sub而不是replace,只允许正则表达式替换而不是纯文本替换。

将文件作为单个字符串而不是逐行读取,可以进行多行匹配和替换。

import re

def replace(file, pattern, subst):
    # Read contents from file as a single string
    file_handle = open(file, 'r')
    file_string = file_handle.read()
    file_handle.close()

    # Use RE package to allow for replacement (also allowing for (multiline) REGEX)
    file_string = (re.sub(pattern, subst, file_string))

    # Write contents to file.
    # Using mode 'w' truncates the file.
    file_handle = open(file, 'w')
    file_handle.write(file_string)
    file_handle.close()

答案 5 :(得分:11)

正如lassevk建议的那样,随时写出新文件,这里有一些示例代码:

fin = open("a.txt")
fout = open("b.txt", "wt")
for line in fin:
    fout.write( line.replace('foo', 'bar') )
fin.close()
fout.close()

答案 6 :(得分:11)

如果你想要一个将任何文本替换为其他文本的泛型函数,这可能是最好的方法,特别是如果你是正则表达式的粉丝:

import re
def replace( filePath, text, subs, flags=0 ):
    with open( filePath, "r+" ) as file:
        fileContents = file.read()
        textPattern = re.compile( re.escape( text ), flags )
        fileContents = textPattern.sub( subs, fileContents )
        file.seek( 0 )
        file.truncate()
        file.write( fileContents )

答案 7 :(得分:8)

一种更加pythonic的方式是使用上下文管理器,如下面的代码:

from tempfile import mkstemp
from shutil import move
from os import remove

def replace(source_file_path, pattern, substring):
    fh, target_file_path = mkstemp()
    with open(target_file_path, 'w') as target_file:
        with open(source_file_path, 'r') as source_file:
            for line in source_file:
                target_file.write(line.replace(pattern, substring))
    remove(source_file_path)
    move(target_file_path, source_file_path)

您可以找到完整的代码段here

答案 8 :(得分:3)

创建新文件,将行从旧文件复制到新文件,并在将行写入新文件之前进行替换。

答案 9 :(得分:3)

扩展@Kiran的答案,我同意更简洁和Pythonic,这增加了编解码器来支持UTF-8的读写:

import codecs 

from tempfile import mkstemp
from shutil import move
from os import remove


def replace(source_file_path, pattern, substring):
    fh, target_file_path = mkstemp()

    with codecs.open(target_file_path, 'w', 'utf-8') as target_file:
        with codecs.open(source_file_path, 'r', 'utf-8') as source_file:
            for line in source_file:
                target_file.write(line.replace(pattern, substring))
    remove(source_file_path)
    move(target_file_path, source_file_path)

答案 10 :(得分:1)

使用hamishmcn的答案作为模板我能够在文件中搜索与我的正则表达式匹配的行并用空字符串替换它。

import re 

fin = open("in.txt", 'r') # in file
fout = open("out.txt", 'w') # out file
for line in fin:
    p = re.compile('[-][0-9]*[.][0-9]*[,]|[-][0-9]*[,]') # pattern
    newline = p.sub('',line) # replace matching strings with empty string
    print newline
    fout.write(newline)
fin.close()
fout.close()

答案 11 :(得分:0)

如果您删除下面的缩进,它将在多行中搜索和替换。 例如,见下文。

def replace(file, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    print fh, abs_path
    new_file = open(abs_path,'w')
    old_file = open(file)
    for line in old_file:
        new_file.write(line.replace(pattern, subst))
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(file)
    #Move new file
    move(abs_path, file)

答案 12 :(得分:0)

如先前答案中所述,

fileinput很简单:

import fileinput

def replace_in_file(file_path, search_text, new_text):
    with fileinput.input(file_path, inplace=True) as f:
        for line in f:
            new_line = line.replace(search_text, new_text)
            print(new_line, end='')

说明:

  • fileinput可以接受多个文件,但是我更喜欢在处理每个文件后立即将其关闭。因此请在file_path语句中放置单个with
  • print语句在inplace=True时不打印任何内容,因为STDOUT被转发到原始文件。
  • end=''中的
  • print是为了消除中间的空白新行。

可以如下使用:

file_path = '/path/to/my/file'
replace_in_file(file_path, 'old-text', 'new-text')

答案 13 :(得分:-1)

对于Linux用户:

import os
os.system('sed -i \'s/foo/bar/\' '+file_path)