【发布时间】:2021-06-02 23:44:02
【问题描述】:
我有一个文件 dates.txt 并试图将文件中的所有“名称”读入临时列表并将它们显示(打印)到屏幕上。在这种情况下,我希望输出为:
乔, 鱼, 米歇尔, 乔纳森
分叉的 repl.it - https://repl.it/@oiuwdeoiuas/Demo-of-2d-array-reading-from-text-file-1 到目前为止我的代码:
import csv
def filecontents():
print("=========READ FIRST NAME===========")
with open("dating.txt",newline="") as f:
reader=list(csv.reader(f))
temporarylist=reader #store copy of the file contents here
for row in reader: #for every row in the file
for i in row:
names=[]
names.append(temporarylist[i][2])
print("The first name in the file is:",names)
filecontents()
示例:dating.txt
JoeBbird,open123,Joe,Bloggs,M,jblogs@gmail.com,22/44/32,Christian,patience,7
FishSmith,open123,Fish,Bloggs,M,jblogs@gmail.com,22/44/32,Christian,laidback,0
MichelleFray,open123,Michelle,Fray,F,jblogs@gmail.com,22/44/32,Christian,leadership,0
JMartin,open123,Jonathan,Martin,M,jblogs@gmail.com,22/44/32,Christian,patience,0
在这里我注意到,假设采用二维数组方法,名称将采用以下格式:0、1、2、3(每行)和第 2 列。
因此,我尝试使用 for 循环遍历行并保持列(字段)标识符静态:
for i in row:
names=[]
names.append(temporarylist[i][2])
错误是:我正在努力理解/纠正。
TypeError: list indices must be integers or slices, not str
据我所知,列表索引 [0,1,2 等] 和 2 是整数。
(temporarylist[i][2])
谁能指出我的代码中的错误并解释我做错了什么。
【问题讨论】: