如何写回在python中打开csv文件 [英] how to write back to open csv file in python
本文介绍了如何写回在python中打开csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试浏览一个csv文件,验证邮政编码并将城市和州写到csv文件的最后一列.
I'm trying to go through a csv file, validate zip codes and write the city and state to the last column in the csv file.
我设法获取了csv数据并获取了城市和州,但是我不知道如何将新数据写入最后一列.像 this 这样的示例显示了如何创建csv ,但不适用于现有的csv.
I managed to get the csv data and get the city and state, but I don't understand how to write the new data to the last column. SO examples like this show how to create a csv, but not work with an existing csv.
到目前为止,这是我的代码:
here is my code so far:
with open("propertyOutput.csv", "rbw") as fp:
reader = csv.DictReader(fp, skipinitialspace=True)
table = [row for row in reader]
for rows in table:
stringNeed = rows['zip']
if not stringNeed.isdigit():
print"not number" #would like to write this to the column
pass
else:
if not len(stringNeed) == 5:
print"string not 5 long" # would like to write this to the column
else:
x = getCityState(stringNeed)
print x # would like to write this to the column
推荐答案
您需要分两个步骤进行操作:
You need to do it in two steps:
-
读取csv文件并存储信息
Read the csv file and store information
import csv
with open("propertyOutput.csv", "rbw") as fp:
reader = csv.DictReader(fp, skipinitialspace=True)
table = [row for row in reader]
header = reader.fieldnames
将信息写入新文件或替换旧文件
Write the information to an new file or replace old file
with open("propertyOutput.csv", "wb") as fp:
writer = csv.DictWriter(fp, header)
for row in table:
if not stringNeed.isdigit():
rows['zip'] = "not number"
# even more stuff to check and edit here
# write the edited row
writer.writerow(row)
这篇关于如何写回在python中打开csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文