J
J
Jlokys2020-06-13 19:46:32
Python
Jlokys, 2020-06-13 19:46:32

How to delete a line with 20 characters in python?

Hello, there is a text file with a large number of lines, and some lines are repeated in it, but not completely, how can I make sure that lines in which less than 20 characters are deleted?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2020-06-13
@Jlokys

with open(file, 'r') as f:
    lines = f.readlines()

new = [line for line in lines if len(line) < 20]

D
Dr. Bacon, 2020-06-13
@bacon

Delete line by line from the file is "expensive", so we create a new file, into which we rewrite the lines from the old one, with the condition that if the line length is less than 20, then we ignore it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question