I'm trying to scrape elements from a page. If the element (always the Middle name) doesn't exist, I can easily use a try/except to get past it in the script... until it tries to save to csv. I'll get a writerow error: NameError: name 'Middle' is not defined
How can I just save 'NA' or a blank field to the csv file?
import csv
First = #site element for first name
Last = #site element for last name
try:
Middle = #site element for middle name
print(Middle)
except:
print('NA')
with open ('test.csv', 'a', newline="") as f:
writer = csv.writer(f)
writer.writerow([First,Last,Middle])
Middle is never set to anything if it doesn't exist in your try except block (which you really should consider excepting the exact error)
try:
Middle = #site element for middle name
print(Middle)
except:
print('NA')
So you try to set Middle
to whatever element is there and if the element doesn't exist you just ignore it. In your exception block set Middle
to N/a instead of just printing N/A:
try:
Middle = #site element for middle name
print(Middle)
except:
Middle = "N/A"
print('NA')
This causes middle to actually have something assigned and thus it won't throw the error you're seeing.
As in the comments, you should define middle outside the try catch block to avoid a scope error:
import csv
First = #site element for first name
Last = #site element for last name
Middle = 'N/A' #this will be overwritten if Middle exists in the try except block below, otherwise it will be 'N/A'
try:
Middle = #site element for middle name
print(Middle)
except:
print('NA')
with open ('test.csv', 'a', newline="") as f:
writer = csv.writer(f)
writer.writerow([First,Last,Middle])