Python:基于现有列将列添加到CSV文件

我已经写了识别和解析所要查找的值所需的内容,我需要帮助将具有已解析的值的列写入csv文件(或新的csv文件).这是我想要做的一些伪代码/有些逼真的Python代码:

# Given a CSV file, this function creates a new CSV file with all values parsed
def handleCSVfile(csvfile):
  with open(csvfile, 'rb') as file:
    reader = csv.reader(file, delimiter=',', lineterminator='\n')
    for row in reader:
        for field in row:
          if isWhatIWant(field):
            parsedValue = parse(field)
            # write new column to row containing parsed value

我已经编写了isWhatIWant和parse函数.如果我需要编写一个全新的csv文件,那么我不确定如何同时打开这两个文件以及如何从一个文件读取另一个文件.

最佳答案
我会这样我猜想isWhatIWant()应该替换掉原位字段.

import csv

def handleCSVfile(infilename, outfilename):
    with open(infilename, 'rb') as infile:
        with open(outfilename, 'wb') as outfile:
            reader = csv.reader(infile, lineterminator='\n')
            writer = csv.writer(outfile, lineterminator='\n')

            for row in reader:
                for field_index, field in enumerate(row):
                    if isWhatIWant(field):
                        row[field_index] = parse(field)
                writer.writerow(row)

这种模式经常发生,导致行很长.有时,将打开逻辑和文件逻辑分解为一个不同的函数可能会有所帮助,如下所示:

import csv

def load_save_csvfile(infilename, outfilename):
    with open(infilename, 'rb') as infile:
        with open(outfilename, 'wb') as outfile:
            reader = csv.reader(infile, lineterminator='\n')
            writer = csv.writer(outfile, lineterminator='\n')

            read_write_csvfile(reader, writer)

def read_write_csvfile(reader, writer)
    for row in reader:
        for field_index, field in enumerate(row):
            if isWhatIWant(field):
                row[field_index] = parse(field)
        writer.writerow(row)

这使代码模块化,从而使您更轻松地更改逻辑上彼此独立地处理文件和格式的方式.

其他提示:

>不要命名变量文件,因为这是内置函数.当您最不希望看到这些名称时,将这些名称隐藏起来会刺痛您.
> delimiter =’,’是默认设置,因此您无需显式指定它.

转载注明原文:Python:基于现有列将列添加到CSV文件 - 代码日志