Home > front end >  How to delete lines which contains only numbers in python?
How to delete lines which contains only numbers in python?

Time:11-02

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?

CodePudding user response:

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

CodePudding user response:

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)
  • Related