我迫切需要你的帮助,因为我对以下案件有点痴迷:
全部,我想要做的是将包含一些指定字符串的行重写到另一个csv文件中。
我正在尝试在StackOverflow上找到各种选项,但这些都不适用于我的情况。
到目前为止我所拥有的:
import csv
with open("origin.csv") as file, open('results.csv','wb') as resultfile:
originreader=csv.reader(file, delimiter=";')
writer=csv.writer(resultfile)
for row in originreader:
if "Windows Server 2008 R2 for x64" in row:
writer.writerow(row)
原始文件如下:
Date;Product;Product Family;Platform;Article;Download;Details
04/12/2002;Windows Vista Service Pack 2;Windows;;3146963;Security Update;CVE-2016-0147
04/12/2002;Windows Server 2008 for 32-bit Systems Service Pack 2;Windows;;3146963;Security Update;CVE-2016-0147
04/12/2002;Windows Server 2008 R2 for x64-based Systems Service Pack 1;Windows;;3146963;Security Update;CVE-2016-0147
04/12/2002;Windows Server 2012 R2 (Server Core installation);Windows;;3146963;Security Update;CVE-2016-0147
04/12/2002;Windows 10 Version 1511 for 32-bit Systems;Windows;;3147458;Security Update;CVE-2016-0147
我希望我能清楚地解释自己。 因为我是初学者,请宽容,这是我在Python中运行的第一个项目。
提前致谢。 鲍尔泰克
答案 0 :(得分:0)
我会使用pandas来完成这项任务和代码:
import pandas as pd
df = pd.read_csv('origin.csv', sep=";")
df_new = df[df['Product']=='Windows Server 2008 R2 for x64']
# or df_new = df[df['Product'].str.contains('Windows Server 2008 R2 for x64')]
df_new.to_csv('my_new.csv')
希望这会有所帮助
答案 1 :(得分:0)
import csv
with open("origin.csv", "r") as file:
originreader=csv.reader(file)
header = next(originreader)
found_data = []
for row in originreader:
new_data = dict(zip(header, row))
if "Windows Server 2008 R2 for x64" in new_data.get("Product"):
found_data.append(row)
with open('results.csv','w') as resultfile:
write = csv.writer(resultfile)
write.writerow(header)
write.writerows(found_data)
答案 2 :(得分:0)
尝试以下代码:
import csv
with open("origin.csv") as file, open('results.csv','w') as resultfile:
originreader=csv.reader(file, delimiter=";")
writer=csv.writer(resultfile)
for row in originreader:
if "Windows Server 2008 R2 for x64" in row[1]:
writer.writerow(row)