Jonathon
Jonathon

Reputation: 271

Python - Remove line with less than "x" number of characters while preserving blank lines

I'm opening a text file with columns and rows. Some rows have more characters than others and I am trying to delete lines that only have <# amount of characters.

The file also contains some blank spacer lines that I need to keep preserved in the file.

with open(outfile) as f, open(outfile2,'w') as f2:
     for x in f:
           if (':') not in x and (',') not in x:
               newline=x.strip()+'\n'
               if len(newline.rstrip()) >= 43:
                   f2.write(newline)

The first if-statement strips some lines of text in the file that I do not want while also adding those extra spacer lines that i need. The second if-statement attempts to get rid of the lines of data that have <# of characters, but this command also gets rid of those blank spacer lines that I need to preserve. How can I get rid of those lines containing <# of characters while preserving the spacer lines?

Upvotes: 1

Views: 1521

Answers (2)

Kenstars
Kenstars

Reputation: 660

with open(outfile) as f, open(outfile2,'w') as f2:
     for x in f:
           if not x.strip().replace("\n",""):
              f2.write(x)
              continue
           elif (':') not in x and (',') not in x:
               newline=x.strip()+'\n'
               if len(newline.rstrip()) >= 43:
                   f2.write(newline)

I guess this additional if statement will solve your problem. If it doesn't you can create a variation of conditional statement that will.

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use the following consolidated approach:

with open(outfile) as f, open(outfile2, 'w') as f2:
    for line in f:
        line = line.strip()
        if not line or (':' not in line and ',' not in line and len(line) >= 43):
            f2.write(line + '\n')

The crucial if statement allows to write either an empty line or a line that meets the needed condition.

Upvotes: 1

Related Questions