My code below checks the validity of postcodes with a regular expression. The postcodes are given in a form of an array. The for loop checks the validity of each postcode with the given regular expression. Now I want to write all the valid postcodes into a csv file. Below is my code:
import csv
import re
regex = r"(GIR\s0AA)|((([A-PR-UWYZ][0-9][0-9]?)|(([A-PR-UWYZ][A-HK-Y][0-9]((BR|FY|HA|HD|HG|HR|HS|HX|JE|LD|SM|SR|WC|WN|ZE)[0-9])[0-9])|([A-PR-UWYZ][A-HK-Y](AB|LL|SO)[0-9])|(WC[0-9][A-Z])|(([A-PR-UWYZ][0-9][A-HJKPSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))))\s[0-9][ABD-HJLNP-UW-Z]{2})"
postcodes = ['$%±()()','XX XXX','A1 9A','LS44PL','Q1A 9AA','V1A 9AA','X1A 9BB','LI10 3QP','LJ10 3QP','LZ10 3QP','A9Q 9AA','AA9C 9AA','FY10 4PL','SO1 4QQ','EC1A 1BB','W1A 0AX','M1 1AE','B33 8TH','CR2 6XH','DN55 1PT','GIR 0AA','SO10 9AA','FY9 9AA','WC1A 9AA']
for x in postcodes:
if(re.findall(regex,x)):
with open('test2.csv','w',newline='') as fp:
a = csv.writer(fp)
a.writerows(x)
The problem with the code is it does not write all the valid postcodes into the csv file, instead it only write the last postcode (WC1A 9AA) in the following format:
W
C
1
A
9
A
A
I don't know where I am making the mistake. Please help.
with open(and the following line to come before your for loopwriterows()expects the argument to be a list of rows, you're calling it with a single string. So it splits the string up into a list of characters, and each character is a row.writerow()to write one row at a time.writerows().