指定增量文件名

2024-10-04 01:34:50 发布

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

我需要在一个文件中搜索一些字符串,并将其中的内容复制到一个单独的文件中

例如,“Hello”在一个文件中重复多次。我想将这些“Hello”之间的文本复制到一个文件中。每次“Hello”重复后面的文本时,它都需要转到一个新文件

请确认我在下面的脚本中使用的逻辑是否正确,以及它给我的缩进错误从我的'如果'循环

import re

text_file = "Hello.txt"
search1 = "Hello"
outfile = "charlie"
write1 = False
x = 0

with open(text_file , "r") as infile:
    fi = infile.readlines()
with open("outfile%s" % x, "w") as fo:
    fo.write("============================================ \n")
    for line in fi:
        if search1 in line:
            write1 = True
            x +=1
            fo.write(line)
        elif write1:
            fo.write(line)

Tags: 文件text文本helloaswithlineopen
1条回答
网友
1楼 · 发布于 2024-10-04 01:34:50

试试这个

text_file = 'Hello.txt'
search_key = 'Hello'
out_file = 'charlie_%d.txt'
current_file = None
occurrence = 0

with open(text_file, 'r') as input_file:
    try:
        for src_line in input_file:
            if search_key in src_line:
                # searched text is found, writing to file
                occurrence += 1
                if current_file:
                    current_file.close()
                current_file = open(out_file % occurrence, 'w')
                current_file.write("============================================ \n")
                current_file.write(src_line)
            elif current_file:
                # no searched text, write line to already open file
                current_file.write(src_line)
    finally:
        if current_file:
            current_file.close()

相关问题 更多 >