使用python替换文本文件中的多行

2024-10-02 22:31:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何在python中替换一个字符串,但我正在努力使其工作,可能是因为这是一个文本块,而不是我想要替换的一行。在

我有一堆文本文件,其中在多个位置重复了以下文本块:

                   LIVEBLAH Information Provided By:
                              BLAH ONLINE
          A division of Blahdeblah BlahBlah Information, Inc.

Washington, DC                    New York, NY                  Chicago, IL
Los Angeles, CA                     Miami, FL                    Dallas, TX

          For Additional Information About LIVEBLAH, Call
                           1-800-XXX-XXXX
                 or Visit Us on the World Wide Web at
                       http://www.blahdeblah.com

我想用字符串“start body”替换出现的每一个文本块

这是我正在尝试的代码:

import os,glob
path = 'files'
key="""
                      LIVEBLAH Information Provided By:
                                   BLAH ONLINE
               A division of Blahdeblah BlahBlah Information, Inc.

Washington, DC                    New York, NY                  Chicago, IL
Los Angeles, CA                     Miami, FL                    Dallas, TX

                For Additional Information About LIVEBLAH, Call
                                1-800-XXX-XXXX
                      or Visit Us on the World Wide Web at
                            http://www.blahdeblah.com"""

for filename in glob.glob(os.path.join(path, '*.txt')):
    with open(filename, 'r') as f:
        # read entire file into file1
        file1 = f.read()

        # replace block of text with proper string
        file1 = file1.replace(key, "start body")

        # write into a new file
        with open(filename+'_new', 'w') as f:
            f.write(file1)

有人能告诉我为什么replace()方法不能处理文本块吗?我该怎么做才能让它成功呢?在

编辑-- 我尝试了另一种方法:

^{pr2}$

这给出了一个奇怪的结果——对于某些文件来说,它工作得很好。对于其他人,它只将字符串“LIVEBLAH Information By:”替换为“start body”,但文本块的其余部分保持原样。对于其他一些情况,index()会引发一个错误,指出它在文件中找不到字符串“LIVEBLAH Information Provided By:”,尽管它显然就在那里。 怎么回事?在


Tags: ofpath字符串文本byinformationwithbody
1条回答
网友
1楼 · 发布于 2024-10-02 22:31:02

由于制表符和换行符将分别编码为'\t'和'\n'或'\r'(取决于用于创建文件的操作系统或文件编辑器),所以我建议您获取文本文件的unicode转储并在replace命令中使用该字符串。否则,您可能会将tab解释为多个空格,依此类推。在

相关问题 更多 >