基于模式拆分文本文件,并具有嵌入在fi中的动态输出文件名

2024-04-23 15:24:48 发布

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

我有以下格式的文本文件

国家:Cntry-190605-00001

读数
读数
读数
读数
读数
读数
读数
读数

分隔符

国家:Cntry-190605-00002

读数
读数
读数
读数
读数
读数
读数
读数

分隔符

我可以用下面的代码在分隔符处将文本文件拆分为多个文件。我的问题是如何将输出文件名设置为Cntry-190605-00001.txt,Cntry-190605-00002.txt,Cntry-190605-00003.txt……..Cntry-190605-00020.txt,其中Cntry-type,190605-date,00008=该天的递增序列号。(每天重新开始)?我正在考虑使用正则表达式来指定输出文件名,但是下一个输出文件的日期和读取标识符将如何更改?你知道吗

只在Python中寻找解决方案。非常感谢。你知道吗

input_file = "Test.txt"

with open(input_file, "r") as f:
    op = []
    i = 1
    for line in f:
        if line.strip():  
           op.append(line)
        if line.strip() == "Delimiter":
           output = open(input_file + '%d.txt' % i,'w')
           output.write(''.join(op))
           output.close()
           i+=1
           op = []

当前我的输出文件是

Test.txt1
Test.txt2
Test.txt3

预期输出为

Cntry-190605-00001.txt
Cntry-190605-00002.txt
Cntry-190605-00003.txt

Tags: 文件testtxtinputoutput文件名lineopen
3条回答

为此,需要从文本文件本身获取文件名。看看这是否有效:

output_filename = ''
for line in f:
    if line.strip():  
       op.append(line)
    if(line.strip().split(:)[0] == "Country"):
       output_filename = line.split(:)[1].strip() 
    if line.strip() == "Delimiter":
       output = open(output_filename,'w')

我会在以Country开头的行上打开一个新文件,然后复制那里的所有内容,直到找到Delimiter

with open(input_file) as f:
    copy = False
    out = None
    for line in f:
        if copy:
            _ = out.write(line)
            if line.strip() == 'Delimiter':
                out.close()
                copy = False
        elif line.strip().startswith('Country'):
            file = line.split(':', 1)[1].split()[0]
            out = open(file + '.txt', 'w')
            _ = out.write(line)
            copy = True
    if out and not out.closed:
        out.close()

带有re的版本,它使用提供的数据创建两个文件Cntry-190605-00001.txtCntry-190605-00002.txt,每个文件都有各自的数据。你知道吗

import re

data = '''Country: Cntry-190605-00001

Readings
Readings
Readings

Delimiter

Country: Cntry-190605-00002

Readings
Readings
Readings

Delimiter'''

names = re.findall(r'Country: (Cntry-\d+-\d+)', data)

for name, p in zip(names, re.findall(r'(.*?Delimiter)\s*', data, flags=re.DOTALL)):
    with open(name + '.txt', 'w') as f_out:
        f_out.write(p)

相关问题 更多 >