remove empty last line from string (output from pipe)
Question: I like to remove the empty line after my output:

    
    
    #!/usr/bin/python
    
    os.system("find /home/pi/bsp/musik/musik/ -name ""*.mp3"" | shuf -n 1 > /home/pi/bsp/musik/musik/track")
    

What I get is:

    
    
    >>>cat track
    /home/pi/bsp/musik/musik/2/Little Green Bag - George Baker Selection - Reservoir Dogs.mp3 
    

But when I print the file in Python its a different story:

    
    
    >>>sudo python play.py
    /home/pi/bsp/musik/musik/2/Lilly Allen - Fuck You.mp3
    
    >>>> 
    

...with a extra line in the end.

I like to pass track to omxplayer but with the additional line in the end
there is no way...so I thought it can´t be to hard to get rid of it:

I tried to save a to a new file and remove the empty line with:

    
    
    os.system("sed '/^$/d' /home/pi/bsp/musik/track > /home/pi/bsp/musik/tt")
    os.system("mv /home/pi/bsp/musik/tt /home/pi/bsp/musik/track ")
    

or remove it right in the pipe with:

    
    
    sed '/^$/d'
    

or remove it from the sting with:

    
    
    text = os.linesep.join([s for s in text.splitlines() if s])
    

or:

    
    
    track[:track.rfind('\n')]
    

And after all nothing worked so far.

Could please someone give the tree in my way a push?


Answer: Assuming `play.py` is `print`ing the contents of the file, the extra line at
the end is coming from the `print` statement. If you need to output the
contents of the file with Python, you can use `sys.stdout.write` instead of
`print`, or `rstrip('\n')` the string, or put a comma at the end of the print
statement, or use the print function with `end=''`. If you're directing input
to OMXPlayer with shell redirection or something like that, it'll probably
work fine without any extra effort.

    
    
    import sys
    sys.stdout.write(file_contents)
    

or

    
    
    print file_contents.rstrip('\n')
    

or

    
    
    print file_contents,
    

or

    
    
    from __future__ import print_function
    
    print(file_contents, end='')
    

