Wednesday, November 2, 2022

[FIXED] How to delete lines which contains only numbers in python?

Issue

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


Answered By - wwii
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.