'how to write a csv file in another csv file in python without pandas
I am a beginner in python, I want to read a csv file and create a second csv file with with some of the data from the first csv.I did this but the second file have only the header
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
Solution 1:[1]
I assume fieldnames is a subset of all the columns. In that case, you need to use extrasaction='ignore'.
An example with an NBA dataset as I don't have your FIFA dataset.
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | brb |
