简体   繁体   English

将行从一个文本文件复制到另一个文本文件直到找到匹配文本的 Python 代码

[英]Python code to copy lines from one text file to other till matching text is found

Lets say my abc.txt file contains below lines假设我的 abc.txt 文件包含以下几行

Information: 
Device 1 information is displayed below 
Device name is ABCD
Firmware version is 1.0.0
Hardware version is 1.0.0
Software version is 0.0.1
Flashed date 1-1-2020
Information: 
Device 2 information is displayed below
Device name is EFGH
Firmware version is 1.0.1
Hardware version is 1.2.0
Software version is 0.0.1
Flashed date is 2.1.2020
Information: 
Device 3 information is displayed below
Device name is IJKL
Firmware version is 1.0.1
Hardware version is 1.2.0
Software version is 0.0.1
Flashed date is 3.1.2020

Copy lines till next "Information" string is found in abc.txt file to xyz.txt file.复制行,直到在 abc.txt 文件中找到下一个“信息”字符串到 xyz.txt 文件。

Expected output in xyz.txt: xyz.txt 中的预期输出:

Information: 
Device 1 information is displayed below 
Device name is ABCD
Firmware version is 1.0.0
Hardware version is 1.0.0
Software version is 0.0.1
Flashed date 1-1-2020

abc.txt file to uvw.txt file. abc.txt 文件到 uvw.txt 文件。

Information: 
Device 2 information is displayed below
Device name is EFGH
Firmware version is 1.0.1
Hardware version is 1.2.0
Software version is 0.0.1
Flashed date is 2.1.2020

Simple string.split() can do your work.简单的string.split()可以完成您的工作。

lis = string.split('Information: Device')

This will output这将输出

['',
 ' 1 information is displayed below Device name is ABCD Firmware version is 1.0.0 Hardware version is 1.0.0 Software version is 0.0.1 Flashed date 1-1-2020 ',
 ' 2 information is displayed below Device name is EFGH Firmware version is 1.0.1 Hardware version is 1.2.0 Software version is 0.0.1 Flashed date is 2.1.2020 ',
 ' 3 information is displayed below Device name is IJKL Firmware version is 1.0.1 Hardware version is 1.2.0 Software version is 0.0.1']

This can be now further modified as这现在可以进一步修改为

lis.remove('')
for i in range(len(lis)):
    lis[i] = 'Information: Device' + lis[i]

This will output the required result, ie,这将输出所需的结果,即

['Information: Device 1 information is displayed below Device name is ABCD Firmware version is 1.0.0 Hardware version is 1.0.0 Software version is 0.0.1 Flashed date 1-1-2020 ',
 'Information: Device 2 information is displayed below Device name is EFGH Firmware version is 1.0.1 Hardware version is 1.2.0 Software version is 0.0.1 Flashed date is 2.1.2020 ',
 'Information: Device 3 information is displayed below Device name is IJKL Firmware version is 1.0.1 Hardware version is 1.2.0 Software version is 0.0.1']

All the list elements can now one-by-one be appended to different txt files.现在可以将所有列表元素一一附加到不同的 txt 文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM