PYPDF2 - Extracting all pages and converting to CSV

Viewed 1336

I am new to Python and was trying to extract data from PDF into a CSV file and below is the code I am using:

import pdfplumber
import pandas as pd

file = 'Test Slip.pdf'

lines = []

with pdfplumber.open(file) as pdf:
    pages = pdf.pages
    for page in pdf.pages:
        text = page.extract_text()
        for line in text.split('\n'):
            print(line)

df = pd.DataFrame(lines)

df.to_csv('test.csv')

I can see the entire text in my terminal which is great. However, the CSV file is coming blank. Can anyone point out the error in my code?

1 Answers

you forget to append string line to list lines. The issue is that the variable lines is always equal to [] Try with this code:

import pdfplumber
import pandas as pd

file = 'Test Slip.pdf'

lines = []

with pdfplumber.open(file) as pdf:
    pages = pdf.pages
    for page in pdf.pages:
        text = page.extract_text()
        for line in text.split('\n'):
            lines.append(line)
            print(line)

df = pd.DataFrame(lines)

df.to_csv('test.csv')
Related