简体   繁体   English

在python中将数据写入CSV文件

[英]write data into csv file in python

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. for循环使用给定的正则表达式检查每个邮政编码的有效性。 Now I want to write all the valid postcodes into a csv file. 现在,我想将所有有效的邮政编码写入csv文件。 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: 该代码的问题是它没有将所有有效的邮政编码写入csv文件,而是仅以以下格式写入了最后一个邮政编码(WC1A 9AA):

W
C
1
A 

9
A
A

I don't know where I am making the mistake. 我不知道我在哪里犯错。 Please help. 请帮忙。

There a few issues but the biggest one is the 'w' -- you're wiping out the file each time you write to it! 那里有几个问题,但最大的问题是'w' -每次写入文件时都会将其清除! :) Change that to an 'a' for append. :)将其更改为'a'以进行追加。

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)

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. 通过在循环中设置带有标志“ w”的打开文件命令,它将在每次迭代中删除并创建一个新文件,因此,您只会得到最后的邮政编码。 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. “ fp.close()”与“ with open”语句无关。

如@jcfollower所建议的那样,在open函数中将'w'更改为'a'模式以附加而不是覆盖每个循环中的文件,或仅将with上下文管理器中的for循环移动到with上下文管理器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM