Reputation: 1701
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.
Upvotes: 2
Views: 1909
Reputation: 884
There a few issues but the biggest one is the 'w'
-- you're wiping out the file each time you write to it! :) Change that to an 'a'
for append.
Secondly I'm not sure what you're attempting to do, but if you're trying to write them all on seperate rows
codes = []
for x in postcodes:
if(re.findall(regex,x)):
codes.append([x])
with open('test2.csv','w',newline='') as fp:
a = csv.writer(fp)
a.writerows(codes)
Upvotes: 2
Reputation: 779
With the open file command set with flag "w" in the Loop, it delete and creates a new file in every iteration, hence you only getting the last postcode. This should get you the correct result:
with open('test2.csv','w',newline='') as fp:
for x in postcodes:
if(re.findall(regex,x)):
a = csv.writer(fp)
a.writerows(x)
Yeah, I forgot. "fp.close()" unnessesary with the "with open" statement.
Upvotes: 1
Reputation: 767
Change the 'w'
to 'a'
mode in the open
function to append rather than overwrite the file on each loop, or simply move the for loop inside the with
context manager, as suggested by @jcfollower.
Upvotes: 0