Search code examples
pythonfilefile-read

How to extract necessary content from file in python?


I have a private key file (private.key) with content in the following format

-----BEGIN PRIVATE KEY-----
blahblahblahblahblahblahblahblah
blahblahblahblahblahblahblahblah
blahblahblahblahblahblahblahblah
-----END PRIVATE KEY-----

I am reading the file as follows:

pk = open( 'private.key', 'rb' ).read()

How do I eliminate the first line and last line and extract just the private key content into the variable pk?

Expecting something similar in python to

egrep -v "PRIVATE KEY" private.key | tr -d "\n\r"

Solution

  • you can use

    pk = open( 'file.txt', 'r' ).readlines() #or 'rb' if there's a need
    
    if len(pk) > 2:
        for line in pk[1:-1]:
            print line,
            #or do anything you like to do with line
    

    to avoid processing of first and last line in the lines list