Search code examples
pythonpython-2.7fwrite

How to not print the last line


I am new to python. I want my script to print everything but the last line. I tried a [:-1] but I cant get it work. I know the code below isnt perfect as it is one of my first but it does everything I need it to do expect ... I dont want it to print the very last line of the string. Please help

import requests


html = requests.get("")

html_str = html.content
Html_file= open("fb_remodel.csv",'a')
html_str = html_str.replace('},', '},\n')
html_str = html_str.replace(':"', ',')
html_str = html_str.replace('"', '')
html_str = html_str.replace('T', ' ')
html_str = html_str.replace('+', ',')
html_str = html_str.replace('_', ',')
Html_file.write(html_str[:-1])
Html_file.close()

Solution

  • html_str is a string, not a list.

    You can do something like this:

    txt='''\
    Line 1
    line 2
    line 3
    line 4
    last line'''
    
    print txt.rpartition('\n')[0]
    

    Or

    print txt.rsplit('\n',1)[0]
    

    The different between rpartition and rsplit can been seen in the docs. I would choose between one or the other based on what I wanted to happen if the split character is not found in the target string.

    BTW, You may want to write your file open this way:

    with open("fb_remodel.csv",'a') as Html_file:
        # blah blah
        # at the end -- close is automatic.  
    

    The use of with is a very common Python idiom.

    If you want a general method of dropping the last n lines, this will do it:

    First create a test file:

    # create a test file of 'Line X of Y' type
    with open('/tmp/lines.txt', 'w') as fout:      
        start,stop=1,11
        for i in range(start,stop):
            fout.write('Line {} of {}\n'.format(i, stop-start))
    

    Then you can use a deque are loop and do an action:

    from collections import deque
    
    with open('/tmp/lines.txt') as fin:
        trim=6                              # print all but the last X lines
        d=deque(maxlen=trim+1)
        for line in fin:
            d.append(line)
            if len(d)<trim+1: continue
            print d.popleft().strip()
    

    Prints:

    Line 1 of 10
    Line 2 of 10
    Line 3 of 10
    Line 4 of 10
    

    If you print the deque d, you can see where the lines went:

    >>> d
    deque(['Line 5 of 10\n', 'Line 6 of 10\n', 'Line 7 of 10\n', 'Line 8 of 10\n', 'Line 9 of 10\n', 'Line 10 of 10\n'], maxlen=7)