如何用python编写一个CSV文件到另一个CSV文件中,而不使用pandas



我是python的初学者,我想读取csv文件并创建第二个csv文件,其中包含来自第一个csv的一些数据。我这样做了,但是第二个文件只有头文件

def create_fifa(infile, outfile):

fieldnames = ["Team", "Nationality", "Position", "Age", "Potential" ,"Name"]
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
data = csv.writer(outfile)
writer.writeheader()
for row in csv.DictReader(infile):
writer.writerow(row)
data.writerow((row))
return outfile

我假设fieldnames是所有列的子集。在这种情况下,您需要使用extrasaction='ignore'

一个NBA数据集的例子,因为我没有你的FIFA数据集。

import csv
infile = 'C:\Users\BRB\nba.csv'
outfile = 'C:\Users\BRB\NewFile.csv'
keepList = ['Name','Team','Position','Age','Height','Weight']
def create_nba(infile, outfile, fields):
infile = csv.DictReader(open(infile))
writer = csv.DictWriter(open(outfile,'w'), fieldnames=fields, extrasaction='ignore')
writer.writeheader()
for row in infile:
writer.writerow(row)
return outfile

f = create_nba(infile, outfile, keepList)

相关内容

  • 没有找到相关文章

最新更新