简体   繁体   中英

Deleting Columns CSV file with Python

I'm trying to delete multiple columns in a csv file with python, but my code just delete the columns on the first line... any solution?

Here is my code in Python 3.5:

import csv
with open("source.csv","r") as source:
    rdr= csv.reader( source )
    with open("result.csv","w") as result:
        wtr= csv.writer( result )
        for r in rdr:
            wtr.writerow( (r[0], r[1], r[3], r[4]) )

And my csv file before i run the python script:

1 row - Policy Name,Client Name,Job Duration,Protected,Schedule/Level Type,Job Start Time,Job End Time,Job Directory,Job Status

2 row -
 PRD19_CABFLAFPRD01_9999CA2,cabflafprd01,15:11:32,"11,161,482.25",Full,"Sep 4, 2017 7:31:09 AM","Sep 4, 2017 10:42:41 PM",/cabflafprdp/grupos,Successful,,,,,,,,

3 row - PRD19_CABFLAFPRD01_9999CA0,cabflafprd01,09:26:50,"4,673,460.75",Full,"Sep 4, 2017 7:31:09 AM","Sep 4, 2017 4:57:59 PM",/cabflafprdp/homedir,Successful,,,,,,,,

After:

1 - Policy Name,Client Name,Protected,Schedule/Level Type

2 - PRD19_CABFLAFPRD01_9999CA0,cabflafprd01,08:29:51,0,Full,"Jun 1, 2017 4:30:16 AM","Jun 1, 2017 1:00:07 PM",/cabflafprdp/homedir,Successful,,,

3 - PRD19_CABFLAFPRD01_9999CA0,cabflafprd01,08:28:07,"4,723,908",Full,"Jun 1, 2017 4:32:00 AM","Jun 1, 2017 1:00:07 PM",/cabflafprdp/homedir,Successful,,,

Pandas is a great option for each row when you create the data frame name them using names = "abcde" then each column will have a letter then next command

import pandas as pd

df1 = pd.read_csv('source', names = 'abc', header = 0)
df2 = df1.drop('b', axis = 1)

print (df2)

Then output the file back to a csv

df3 = data.to_csv('source_with_dropped_columns')

The second line of code will drop the column named "b"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM