每次循环新行时,您都会重置sep。假设文件有 2 行:
with open('2018-01-btp-street.csv', 'r') as file:
for row in file: # first loop:
sep = row.split(',') # sep now contains all items in the first row that were separated by commas.
#second loop: sep now only(!) contains all items in the SECOND row that were separated by commas.
您可以通过在循环内 sep 的定义之后添加 print(sep) 来测试这一点。
现在,您需要的是每行的第二列。 string.split(other_string)返回由other_string 分隔的字符串的所有单独片段的列表。因此,您可以将这些列表中的每一个都存储在一个新列表中,如下所示:
all_values = []
with open('2018-01-btp-street.csv', 'r') as file:
for row in file:
sep = row.split(',')
all_values.append(sep) # this is the important part. sep will still be reset every loop, but the values are now stored in all_values.
现在,您有一个列表列表。要获取所有列表的第二个值,请执行
for l in all_values:
print(l[1])
你也可以使用 list comprehension 来做同样的事情:
with open('2018-01-btp-street.csv', 'r') as file:
all_values = [row.split(',') for row in file]
all_values 看起来像这样:
[[row1_col1, row1_col2, row1_col3, ...], [row2_col1, row2_col2, row2_col3,...], ...]
或者,获取所有列的列表:
with open('2018-01-btp-street.csv', 'r') as file:
all_values = [row.split(',') for row in file]
all_columns = [[l[i] for l in all_values] for i in range(len(all_values[0]))]
这会给你一个看起来像的列表
[[row1_col1, row2_col1, row3_col1], [row1_col2, row2_col2, row3_col2], ...]
现在你可以使用
print(all_columns[1])
获取第二列的所有值。