用Python编辑文件并将结果写在新文件上,但仅在特定区域

Codeburn

我想制作一个脚本,执行以下操作:

我有file_ori.txt,它的内容是这样的(数字只是行号而不是实际文本)

1 This is test line with random text
2 This is also a line with lalala text
3 This is that and this and that of a line
4 start sequence
5 This isn't also a line with lalala text
6 This is test line with random text
7 This is also a line with lalala text
8 end sequence
9 This is test line with random text

我要帮忙的是在整个文件中将单词“ line”更改为单词“ Pine”,但只在start sequence之间传递新文件中的更改,end sequence结果是:

1 This is test line with random text
2 This is also a line with lalala text
3 This is that and this and that of a line
4 start sequence
5 This isn't also a Pine with lalala text
6 This is test Pine with random text
7 This is also a Pine with lalala text
8 end sequence
9 This is test line with random text

对于我来说至关重要的是,我不想在替换之前而是在之后才拆分文件。我必须阅读全文。

f = open(file_ori.txt, "r")
full_read = f.read()

full_read = full_read.replace('line', 'Pine')

............. I don't know how to continue

f = open(file_ori_edit.txt, 'w')
    f.write(full_read)
    f.close()

谢谢。

拉克什

这是一种方法。

例如:

start = 'start sequence'
end = 'end sequence'
parse = False
result = []
with open(filename) as infile:
    for line in infile:      #Iterate each line
        line = line.strip()
        if start == line:    #check for start sequence
            parse = True
        if end == line:      #check for end sequence
            parse = False

        if parse:   #Replace ONLY between sequence
            line = line.replace('line', 'Pine')
        result.append(line+"\n")

with open(filename, "w") as outfile:
    outfile.writelines(result)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

连接特定行并将结果输出到新文件中

在python中读取文件的特定位置并将其写入新文件中

如何从文件中提取特定行并将特定行保存到python中的每个新文件中

用新文件更新文件

从多个文件读取数据并将数据写入新文件会产生意外结果?

如何通过Java过滤文本文件并将结果保存到新文件

Python代码问题 - 试图创建一个定位文件的脚本,编辑它并将其另存为新文件

比较python中的两个文件并将行差异保存在新文件中

使用pathlib在python中创建新文件夹并将文件写入其中

Python:从XML文件中查找和删除子级并将其输出到新文件

Python获取最新文件列表并将其与旧文件列表进行比较

Python在文件中查找字符串,编辑行并保存到新文件

查找包含特定字符串的行并将其添加到新文件中

复制具有特定字符的行并将其粘贴到新文件中

在 Linux shell 中读取文本并将某些特定行写入新文件

我什么时候不能在Wordpress的主题编辑器上更新文件?

创建新文件?

Python ssh查找最新文件

目录中的Python最新文件

Python从磁盘刷新文件

Python元素树写入新文件

在python 2.7中编写新文件

创建新文件并将其包含到python包中

无法使用 python 替换 csv 中的字符并将它们保存在新文件中

如何使用Python删除部分XML数据并将其写入新文件

用1个新文件替换多个文件

Python-将列表中的特定文件复制到新文件夹中

从 tar 文件中提取更新文件的特定版本

查找包含特定文件的最新文件夹