I am trying to save the results of a regex .findall() search into a csv but am having difficulties appending the result to an output file.
As I am still very new to Python I am attempting to limit this problem to using only the csv and re libraries - but if there is a far easier way (i.e. in pandas) that would also be helpful to know.
How would one copy the entire contents of the input CSV to the output CSV and add the postcode / found regular expression to the line it was found on?
Are there any obvious forms of error checking or other things that I am missing?
Does a better method exist to add the header of the input CSV automatically to the output CSV without explicitly specifying them?
Is it possible to do this using DictWriter? As I had originally attempted.
import csv, re
pattern = r'[A-Z]{1,2}[0-9R][0-9A-Z]?[0-9][A-Z]{2}'
postcodes = []
with open(r'Postcode/addressin.csv', 'r') as csvinput:
csv_reader = csv.DictReader(csvinput)
with open(r'Postcode/addressout.csv', 'w', newline='') as csvoutput:
fieldnames = ['Address', 'Name']
csv_writer = csv.writer(csvoutput)
csv_writer.writerow(fieldnames)
for line in csv_reader:
postcodes = re.findall(pattern, line["Address"])
csv_writer.writerow(postcodes)
Example Data:
Address,Name,Lat,Long,2016 Sales,Type
48 Park Avenue, LATTON, SN6 4SZ,Nikki Yellowbeard,-23.17549,36.74641,9727,AA
IV21 1TD 116 Walwyn Rd CHARLESTOWN,Jonh Doe,-10.98309,156.41854,11932,AE