Removing spaces and empty lines from a file Using Python

前端 未结 5 2018
傲寒
傲寒 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 05:43

    strip() removes leading and trailing whitespace characters.

    with open("transfer-out/" + file, "r") as f:
        for line in f:
            cleanedLine = line.strip()
            if cleanedLine: # is not empty
                print(cleanedLine)
    

    Then you can redirect the script into a file python clean_number.py > file.txt, for example.

    0 讨论(0)
  • 2020-12-11 05:44

    Change your 'lines' line to use the following generator and it should do the trick.

    lines = (line.strip() for line in fh.readlines() if len(line.strip()))
    
    0 讨论(0)
  • 2020-12-11 05:46

    Another one with list comprehension:

    clean_lines = []
    with open("transfer-out/" + file, "r") as f:
        lines = f.readlines()
        clean_lines = [l.strip() for l in lines if l.strip()]
    
    with open("transfer-out/"+file, "w") as f:
        f.writelines('\n'.join(clean_lines))
    
    0 讨论(0)
  • 2020-12-11 06:01

    This should work as you wish:

    file(filename_out, "w").write(file(filename_in).read().strip())
    

    EDIT: Although previous code works in python 2.x, it does not work python 3 (see @gnibbler comment) For both version use this:

    open(filename_out, "w").write(open(filename_in).read().strip())
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题