Select data from existing file

Asked by At

I have a Tab delimited file that has data in the following order (about 2400 rows)-


| SNO | Model#|Agent Name  | cost | MRP |    date    | Discount |
|---------------------------------------------------------------|
|   1 | 1112B | Chris      |  689 | 998 | 01/01/2014 | 5%       |

I want to

(1) Take out the Name and corresponding MRP and store it into a new file

expected outcome should be the following (stored in a new excel file or tab delimited text file)


| AgentName | MRP  |
|-----------|------|
| Chris     |  988 |
| A         |  111 |
| B         | 222  |
| C         |  333 |
| D         |  444 |


I started doing the following but could not finalize -

with open ('/path.txt') as f:
    for l in f:
        print l.strip().split("\t")

2 Answers

1
amanb On

If the file is available in csv format, then you can do it with pandas:

import pandas as pd
df = read_csv('/path to file.csv', sep='\t')
slice = df[['AgentName','MRP']] 
slice.to_csv('new_file.csv', index=False)
1
krasu On

Using only standard library csv module:

import csv
with open ('Project1.txt', 'rU') as from_fp, open('output.tsv', 'w') as to_fp:
    csv_reader = csv.DictReader(from_fp, dialect=csv.excel_tab)
    csv_writer = csv.writer(to_fp, delimiter='\t')
    csv_writer.writerow(['AgentName', 'MRP'])
    for row in csv_reader:
        csv_writer.writerow([row.get('AgentName'), row.get('MRP')])

Link to demo