我已经编写了识别和解析我正在寻找的值所需的内容,我需要帮助将一列写入带有解析值的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文件,那么我不确定如何同时打开它们并从一个读取和写入另一个。
答案 0 :(得分:3)
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)
这使代码模块化,使您更容易从逻辑中相互独立地更改文件和格式的处理方式。
其他提示:
file
命名为内置函数。隐藏这些名字会在你最不期望的时候咬你。delimiter=','
是默认设置,因此您无需明确指定。