0

I am trying to access my variable but it say name is not defined, Here I read pdf file

def read_pdf(file):

    with open(file, "rb") as f:
        pdf = pdftotext.PDF(f)
    st.write('button clicked',file[:-4]+'.txt')
    with open(file[4:-4]+'.txt', 'a') as f:
        for page in pdf:
            f.write("%s\n" % page)    
    return " ".join(pdf)

if st.button('read_pdf'):
    para = read_pdf('qna/'+filename)
    st.write('length of text: %s' % len(para))

Here I can get length of para.

sentence = st.text_input('Input your Question here:') 
if sentence:
    st.write('length of text: %s' % len(para))
    st.write('length of sentence: %s' % len(sentence))

But here it say

NameError: name 'para' is not defined
Talha Anwar
  • 2,699
  • 4
  • 23
  • 62
  • Perhaps it is a similar case to this: [Variable not defined error, and if statement doesn't execute](https://stackoverflow.com/questions/44999737/variable-not-defined-error-and-if-statement-doesnt-execute) ? – Kostas Mar 27 '21 at 06:57
  • but the if condition is satisfied and the value should be inside variable – Talha Anwar Mar 27 '21 at 07:07
  • Maybe the if condition is not satisfied? What happens if you place `para = read_pdf('qna/'+filename)` outside the if statement? – Kostas Mar 27 '21 at 07:13
  • if the condition is not satisfied then why it print for the first time inside first `if` condition. – Talha Anwar Mar 27 '21 at 07:29
  • 1
    yes, as i am calling function inside if statement, so it should be out of function – Talha Anwar Mar 27 '21 at 07:43

2 Answers2

0

Just initialise para with empty string ,before para = read_pdf('qna/'+filename)

s Hegade
  • 21
  • 5
0

I cannot reproduce the code locally, but I think that the "if" statement evaluates to False, so the code

para = read_pdf('qna/'+filename)
st.write('length of text: %s' % len(para))

is never executed. This is the only way (that I can think of) for your variable "para" to not be defined.

This might also be relevant concerning your streamlit button: Streamlit button works only once

Kostas
  • 99
  • 1
  • 2
  • 7