How to delete lines which contains only numbers in python?

Question:

I have a large text file in Python. Firstly, I want to read the text then, delete lines which have only numbers. Then, I open a new text file and write with my changes.

If the line contains numbers and strings, I want to keep them. I tried with isdigit and regex but I couldn’t…

e.g. I tried: but it deletes all lines that contain numbers.

    if not all(line.isdigit() for line in text_data):

new question:

line1: 324 4234 23456

if I have a line which contains numbers and space only like line1, how I skip them to my new text file?

Asked By: rocinantes

||

Answers:

Strip whitespace from the line before checking if it is all numbers.

for line in text_data:
    if line.strip().isdigit():
        # do what is required for a line with all numbers
    else:
        # do what is required for an alphanumeric line
Answered By: wwii

I think you just need to read the file, filter it if line is not a digit, then write it to a new file:

with open('old.txt') as old, open('new.txt', 'w') as new:
    for line in filter(lambda text: not text.strip().isnumeric(), old): new.write(line)
Answered By: Arifa Chan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.