Hello, everyone, the task is to either delete all the lines or not read them at all.

There are certain categories in which there are unwanted lines, how to implement so that the category "invit" in it is given the data "D", "F", "I", "Q", "B", you need to delete the lines with the data "Q" or do not read lines in this category with these lines.

The situation is such that if you delete all the lines from Q, the output file is not correct. How not to take this line for further manipulations

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

The easiest option is to check each line for compliance with a specific regular expression. Depending on the result: save this line in the output file or not.

Example code (all lines of the input file starting with the character Q will be excluded):

 import re import os pattern = re.compile(r"^Q.*") fin = open(input_filename) fout = open(output_filename, "w") for line in fin.readlines(): if not pattern.match(line): fout.write(line) fin.close() fout.close() os.rename(output_filename, input_filename) 

I leave you to make a suitable regular expression, to handle exceptions, to optimize reading / writing as needed.

  • The situation is such that if you delete all the lines from Q, the output file is not correct. How not to take this line for further manipulations - SVETLANA NOVIKOVA
  • You give an example of a file and specify which lines you want to exclude. - aleks.andr
 # если файл вида ''' [TEST] Q2=http://handler/ [invit] A=[123] D=https:/ F=http:// ... ''' import configparser def get_ini_data(file): parser = configparser.ConfigParser() parser.read(file) for category in parser.sections(): for var in parser.options(category): if not (category == 'invit' and var in ["d", "f", "i", "q", "b"]): data = parser.get(category, var) yield category, var, data for category, var, data in get_ini_data('test.ini'): print(category, var, data)