Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否以升序数字顺序生成新的csv文件和订单数据?_Python_Python 3.x_Csv - Fatal编程技术网

Python 是否以升序数字顺序生成新的csv文件和订单数据?

Python 是否以升序数字顺序生成新的csv文件和订单数据?,python,python-3.x,csv,Python,Python 3.x,Csv,我编写了一个代码,在“import_data.csv”文件中包含的每个邮政编码上实现给定的正则表达式。然后,它生成一个新的csv文件“failed_validation.csv”,其中包含验证失败的所有邮政编码。两个文件的结构均采用以下格式: row\u id邮政编码 134534 AABC 123 243534 AACD 4PQ 534345 QpCD 3DR ... ... 以下是我的代码: import csv import re regex = r"(GIR\s0AA)|((([A-

我编写了一个代码,在“import_data.csv”文件中包含的每个邮政编码上实现给定的正则表达式。然后,它生成一个新的csv文件“failed_validation.csv”,其中包含验证失败的所有邮政编码。两个文件的结构均采用以下格式:

row\u id邮政编码
134534 AABC 123
243534 AACD 4PQ
534345 QpCD 3DR
... ...
以下是我的代码:

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})"

codes = []

with open('../import_data.csv','r') as f:
    r = csv.reader(f, delimiter=',')
    for row in r:

     if not(re.findall(regex, row[1])):
      codes.append([row[0],row[1]])

with open('failed_validation.csv','w',newline='') as fp:
    a = csv.writer(fp)
    a.writerows(codes)

代码工作正常,但我实际需要的是新文件中的邮政编码需要按照行id按升序数字顺序排序。我知道如何使用Python生成新文件,但我不知道如何将文件中的数据按数字升序排序。

在写入文件之前对代码列表进行排序

headers = codes[0]
codes = sorted(codes[1:])
with open('failed_validation.csv','w',newline='') as fp:
  a = csv.writer(fp)
  a.writerow(header)
  a.writerows(codes)

这将执行此操作并保留标题行:

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})"

codes = []
with open('import_data.csv', 'r', newline='') as fp:
    reader = csv.reader(fp, delimiter=',')
    header = next(reader)
    for row in reader:
        if not re.findall(regex, row[1]):
            codes.append([row[0],row[1]])

with open('failed_validation.csv', 'w', newline='') as fp:
    writer = csv.writer(fp)
    writer.writerow(header)
    writer.writerows(sorted(codes))

阅读时,将处理过的行放入列表中,并在写出结果之前使用list.sort或全局函数“sorted”对列表进行排序。这将破坏csv文件,因为
code
包含标题行。@ekhumoro有意义。