Skip to main content
 首页 » 编程设计

python之从一个 txt 文件中选取部分并使用 python 复制到另一个文件

2025年05月04日8lyj

我这里有麻烦了。我需要读取一个文件。 txt 文件包含一系列记录,勾选我要将它们复制到新文件中的记录。 文件内容是这样的(这只是一个例子,原文件有30000多行):

AAAAA|12|120 #begin file 
00000|46|150 #begin register 
03000|TO|460  
99999|35|436 #end register 
00000|46|316 #begin register 
03000|SP|467 
99999|33|130 #end register 
00000|46|778 #begin register 
03000|TO|478 
99999|33|457 #end register 
ZZZZZ|15|111 #end file 

必须将以 03000 开头且具有字符“TO”的记录写入新文件。根据示例,文件应如下所示:

AAAAA|12|120 #begin file 
00000|46|150 #begin register 
03000|TO|460  
99999|35|436 #end register 
00000|46|778 #begin register 
03000|TO|478 
99999|33|457 #end register 
ZZZZZ|15|111 #end file 

代码:

file = open("file.txt",'r') 
newFile = open("newFile.txt","w")     
content = file.read() 
file.close() 
# here I need to check if the record exists 03000 characters 'TO', if it exists, copy the recordset 00000-99999 for the new file. 

我进行了多次搜索,但没有找到对我有帮助的东西。 谢谢!

请您参考如下方法:

with open("file.txt",'r') as inFile, open("newFile.txt","w") as outFile: 
    outFile.writelines(line for line in inFile  
                       if line.startswith("03000") and "TO" in line) 

如果你需要上一行和下一行,那么你必须在三元组中迭代inFile。首先定义:

def gen_triad(lines, prev=None): 
    after = current = next(lines) 
    for after in lines: 
        yield prev, current, after 
        prev, current = current, after 

然后像以前一样:

outFile.writelines(''.join(triad) for triad in gen_triad(inFile)  
                   if triad[1].startswith("03000") and "TO" in triad[1])