简体   繁体   中英

Python: Extracting first element from each line of a CSV file

I would like to read from a csv file and add certain things to a list

JFK,John F Kennedy International,5326,5486
ORY,Paris-Orly,629,379
MAD,Adolfo Suarez Madrid-Barajas,1428,1151
AMS,Amsterdam Schiphol,526,489
CAI,Cairo International,3779,3584

Everything in the text file is listed above, I'd like to get the first from every line, so JFK ORY MAD AMS CAI added to a list.

I tried:

with open('Airports.txt', 'r') as f:
    reader = csv.reader(f)
    amr_csv = list(reader)

But this adds the whole text file to the list, and I couldn't get my head around adding it to only the first line

In summary, i'd like help on adding the first line of this text file to a list which is saved as a variable.

I'm pretty sure this will solve your problem

import csv
with open('Airports.txt', 'r') as f:
    reader = csv.reader(f)
    amr_csv = list(reader)
    for line in amr_csv:
        print(line[0])

Or

import csv
with open('Airports.txt','r') as f:
    reader = csv.reader(f)
    amr_csv = [line[0] for line in reader]
    print(amr_csv)

Let's go with something very simple .

This snippet extracts the IATA codes from your CSV file into a list :

with open('airports.txt') as f:
    iata = [i.split(',')[0] for i in f.readlines()]

Code explanation:

Essentially this code is reading each line of the CSV and splitting by comma; then extracting the first element ( [0] ) and adding to a list, using list comprehension .

Output:

['JFK', 'ORY', 'MAD', 'AMS', 'CAI']
import csv

with open('Airports.txt', 'r') as f:
    reader = csv.reader(f)
    example_list = list(reader)

print(example_list)

OUTPUT:

[['JFK', 'John F Kennedy International', '5326', '5486'], ['ORY', 'Paris-Orly', '629', '379'], ['MAD', 'Adolfo Suarez Madrid-Barajas', '1428', '1151'], ['AMS', 'Amsterdam Schiphol', '526', '489'], ['CAI', 'Cairo International', '3779', '3584'], []]

Thank you for anyone who offered help, this is what I ended up settling on as it was what i was looking for, hope this helps anyone with any similar question.

See if this works

import csv

with open('Airports.txt', 'r') as file:
    reader = csv.reader(file)
    amr_csv = list(reader)
    for i in range(len(amr_csv)):
        print(amr_csv[i][0])

You can acces any data in your 2d array by accessing the amr[line][column] .

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