Search code examples
pythonfilenumberstext-files

How to delete lines which contains only numbers in python?


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?


Solution

  • 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