Reputation: 1
The input CSV file is below.
Elements,FileID,Loadcase,Step,Layer,CornerID,E-Strain components IP:E11
41,2,1,0,SectionPoint 1,0,0
41,2,1,0,SectionPoint 1,5,0
41,2,1,0,SectionPoint 1,35,0
In this file, I want to remove the entire CornerID
column and write a new CSV file.
Note: the script should work with header name and remove that column . Not like in the way of Column indices level deleting. because like this I have multiple files, in some files the column number will not be the same.
can anyone help me to get python code for this?
import csv
inputf = "D:\PyLe\csvinput\Report_E-Strain components IP_E11_2_1.csv" outfile = "D:\PyLe\csvinput\Report_E-Strain components IP_E11_2_1_new.csv"
import csv
with open(inputf, newline='') as csvfile:
outfile1 = open (outfile , 'w')
reader = csv.DictReader(csvfile)
for row in reader:
del (row['CornerID'])
spamwriter = csv.writer(outfile1, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(row)
print (type(row))
this code is reading the csv file and deleting that columnl. but its not writing out the new file with csv format.
Upvotes: 0
Views: 1160
Reputation: 3528
You can first read_csv, then drop the column and then save it as a csv using to_csv
import pandas as pd
df = pd.read_csv('your_CSV_file_name')
df.drop(['CornerID'], axis=1, inplace=True)
df.to_csv('path_or_buf_to_save_new_csv')
Upvotes: 1
Reputation: 528
The easiest way to go is to use pandas
. It is a common python module to handle tabular data.
import pandas as pd
csv = pd.read_csv("pathtoyourcsvfile.csv")
csv = csv.drop("CornerID", axis=1)
csv.to_csv("pathtoyournewcsvfile.csv")
Upvotes: 1