How do I extract only the required columns from a txt or csv file and save them as a txt file?

Asked 1 years ago, Updated 1 years ago, 83 views

with open('file name.csv') as file:
    csv_data = []
    for line in file.readlines():
        csv_data.append(line.split(','))

I know how to divide rows and columns.Invoke only the columns you need
I don't know how to save it as a txt file again.
Python is very new to me.<

It doesn't matter if csv is saved as txt in the txt file.
What I need is, assuming that I need columns 1-5, how do I do that?

python csv txt split

2022-09-21 18:37

2 Answers

There can be many ways.

I used the Pandas module, which is used a lot for data processing.

Part of WHO_8COLS.csv.

,Country,CountryID,Continent,Adolescent fertility rate (%),Adult literacy rate (%),Gross national income per capita (PPP international $),Net primary school enrolment ratio female (%),Net primary school enrolment ratio male (%),Population (in thousands) total
0,Afghanistan,1,1,151.0,28.0,,,,26088.0
1,Albania,2,2,27.0,98.7,6000.0,93.0,94.0,3172.0
2,Algeria,3,3,6.0,69.9,5940.0,94.0,96.0,33351.0
3,Andorra,4,2,,,,83.0,83.0,74.0
import pandas as pd
df = pd.io.parsers.read_csv("WHO_8COLS.csv")
sliceData = df.loc[:, 'Country'] #Country column only truncated
Save as sliceData.to_csv('newSliced.csv', index=False) #csv


2022-09-21 18:37

Try it in GO language

The sample.csv is shown below.

first_name,last_name,username
Rob,Pike,rob
Ken,Thompson,ken
Robert,Griesemer,gri
package main

import (
    "encoding/csv"
    "os"
)

func main() {
    rf, _ := os.Open("f:\\sample.csv")
    defer rf.Close()

    r := csv.NewReader(rf)
    records, _ := r.ReadAll()
    saveRecords := [][]string{} // filtered rows
    for _, record := range records {
        saveRecords = append (saveRecords, record[0:2]) // Filter Save only the first and second columns
    }
// Store filtered records in a new file
    wf, _ := os.Create("F:\\sample_new.csv")
    defer wf.Close()
    w := csv.NewWriter(wf)
    w.WriteAll(saveRecords)
}

Results

first_name,last_name
Rob,Pike
Ken,Thompson
Robert,Griesemer


2022-09-21 18:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.