我是新来的,也是Python脚本,但我需要一些关于我的litle脚本的帮助。我有一个CSV
这样的文件:
19928;renet;54;amsterdam
27732;tango;36'rotterdam
ENZ。 ENZ
如何只选择带有阿姆斯特丹的行来写入新文件?
这是我的剧本:
import csv
import os
data = [] #Buffer list
with open(os.path.join("CSV", "verliezen.csv"), "rb") as input_file:
reader = csv.reader(input_file, delimiter=";")
for row in reader:
try:
new_row = [row[0], row[3]]
data.append(new_row)
except IndexError as e:
print e
pass
with open("the_new_csv.csv", "w+") as to_file:
writer = csv.writer(to_file, delimiter=";")
for new_row in data:
writer.writerow(new_row)
答案 0 :(得分:0)
检查行中的最后一个位置是否等于'amsterdam',如下面的代码:
import csv
data = [] #Buffer list
with open("CSV\\verliezen.csv", "rb") as input_file:
reader = csv.reader(input_file, delimiter=";")
for row in reader:
if row[-1] == 'amsterdam':
data.append(row)
with open("the_new_csv.csv", "w+") as to_file:
writer = csv.writer(to_file, delimiter=";")
for new_row in data:
writer.writerow(new_row)