Home > Blockchain >  Extract line from multiple text files
Extract line from multiple text files

Time:01-12

I have multiple text files with the same structure (a1.cnv, a2.cnv, a3.cnv ....). I would like to copy lines that start with "time=" and "value2=" from every cnv file to a new single text file. Can someone please help?

So far I have used this code to find "time=" and "value2=".

import re

errors = []
linenum = 0
pattern1 = re.compile(r"time=")
pattern2 = re.compile(r"value2=")

with open ('a1.cnv', 'rt') as myfile:
   for line in myfile: linenum  = 1
       if pattern1.search(line) != None:
           errors.append((linenum, line.rstrip('\n')))
       if pattern2.search(line) != None:
           errors.append((linenum, line.rstrip('\n')))
   for err in errors: print(err[1])

CodePudding user response:

You can make a list for all the files and use a for loop to read lines with pandas or open(). You can store the output for each file in a new list and make a new csv file containing the output.

CodePudding user response:

Create a new list to store the lines you find. Use the open() function to open the file and call readlines() on the result. then iterate over those lines and use regex to match lines that contain "time=" and "value2=". If it matches, add the line to your list. Repeat for each file. Once you have processed all the files, write the new list of lines to a new file

  •  Tags:  
  • Related