Removing a header and footer from text output with PDFminer I use PDFminer to extract text from a PDF, then I reopen the output file to remove an 8 line header and 8 line footer. Is there a more efficient way to remove the header/footer, either in place or without re-opening/closing the file? Please mention general best practices I did not follow.

# convert PDF to text
def write_txt(pdf):
    outfile = pdf.split("_")[4] + "_" + pdf.split("_")[1] + "_" + \
        pdf.split("_")[0] + ".txt"
    pagenos = set([2,3])

    codec = 'utf-8'
    caching = True
    laparams = LAParams()

    rsrcmgr = PDFResourceManager(caching=caching)
    outfp = file(outfile, 'w+')
    device = TextConverter(rsrcmgr, outfp, codec=codec, laparams=laparams)
    fp = file(pdf, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    for page in PDFPage.get_pages(fp, pagenos):
        interpreter.process_page(page)
    fp.close()
    device.close()
    outfp.close()

    # remove header/footer
    with open(outfile, 'r') as txtin:
        lines = txtin.read().splitlines(True)
    with open(outfile, 'w') as txtout:
        txtout.writelines(lines[8:-8])

    return outfile
This line performs the same string splitting 3 times:


outfile = pdf.split("_")[4] + "_" + pdf.split("_")[1] + "_" + \
    pdf.split("_")[0] + ".txt"



It would be better to split only once, and also to replace the messy string concatenation:

parts = pdf.split("_")
outfile = '{}_{}_{}.txt'.format(parts[4], parts[1], parts[0])




The variables could have better names.
When I see "pdf",
it makes me think of a PDF object.
But in this code it's just the filename string.
So I'd call it pdf_filename.



I don't have this Python library you're using,
and I'm just wondering if you could rewrite all those resources that you close manually (fp, device, outfp) to use the with syntax instead like you used for txtin and txtout.
If that's not possible with this library, then nevermind.