Removing spaces and empty lines from a file Using Python

前端 未结 5 2020
傲寒
傲寒 2020-12-11 05:16

I have a file which contains a value 2000,00.

But it contains spaces after 2000,00 and empty lines.

I want to remove all the spaces and empty lines, if some

5条回答
  •  失恋的感觉
    2020-12-11 06:05

    Functional one :)

    import string
    from itertools import ifilter, imap
    
    print '\n'.join(ifilter(None, imap(string.strip, open('data.txt'))))
    # for big files use manual loop over lines instead of join
    

    Usage:

    $ yes "2000,00  " | head -n 100000 > data.txt
    $ python -c "print '\n'*100000" >> data.txt
    $ wc -l data.txt 
    200001 data.txt
    $ python filt.py > output.txt
    $ wc -l output.txt 
    100000 output.txt
    

提交回复
热议问题