簡體   English   中英

讀取文件並匹配多行

[英]Read a file and match multiple lines

文本文件如下:

    <field>
        </field>

我想匹配塊並在兩個字段標簽之間寫一些東西。 我有以下代碼,這些代碼來自如何在文本文件中搜索字符串?

!/usr/bin/env python3
import mmap
import os

with open('sample.txt', 'rb+', 0) as file, \
     mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
    if s.find(b'<field>\n<\field>') != -1:
        file.write("Hello")

即使使用\\ t檢測選項卡,我的解決方案也不起作用

'<field>\n\t<\field>'

我認為我的問題是如何匹配多行包含空格或制表符的行。 感謝大家。

請參考以下問題: 正則表達式匹配多行文本塊

使用正則表達式,您的目標非常簡單。 以下腳本在變量html找到<field>標簽,並將<text to put between the tags>之間<text to put between the tags>之間。

import mmap
import os
import re

# do logic here

# test for what you want from variable s:

a = re.sub('<field>(.*\n*)<\/field>', '<text to put between the tags>', html)

我得到了答案: Pythonic將行插入文件的方式

該解決方案不使用mmap。 是的,我們不能將數據插入文件,但是可以替換數據。

        target = "<field>Hello</field>"

        with open(os.path.join(root, filename), 'r') as file:
            filedata = file.read()

        # Replace the target string
        filedata = filedata.replace('<field></field>', target)

        # Write the file out again
        with open(os.path.join(root, filename), 'w') as file:
            file.write(filedata)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM