1

我想从 csv 文件中读取并将某些内容添加到列表中

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

上面列出了文本文件中的所有内容,我想从每一行中获取第一个,因此将 JFK ORY MAD AMS CAI 添加到列表中。

我试过:

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

但这会将整个文本文件添加到列表中,我无法将其仅添加到第一行

总之,我想帮助将此文本文件的第一行添加到保存为变量的列表中。

4

4 回答 4

1

我很确定这会解决你的问题

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])

或者

import csv
with open('Airports.txt','r') as f:
    reader = csv.reader(f)
    amr_csv = [line[0] for line in reader]
    print(amr_csv)
于 2020-09-30T20:50:37.757 回答
1
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.

于 2020-10-19T19:07:25.240 回答
0

让我们做一些非常简单的事情。

此代码段将 IATA 代码从您的 CSV 文件中提取到list

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

代码说明:

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']
于 2020-09-30T21:23:37.263 回答
-1

看看这是否有效

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])

您可以通过访问amr[line][column].

于 2020-09-30T21:06:17.707 回答