这听起来像是 Python 的CSV 模块的工作。读取的每一行都作为字符串列表返回。
从文档中借用一个简短的例子:
从 csv 文件读取的每一行都作为字符串列表返回。不执行自动数据类型转换。
一个简短的使用示例:
[这只是打印出每一行]
import csv
with open('some.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
您可以通过使用适当的索引值对行进行索引来访问特定列。
或者,如果您想“手动”执行此操作(每行由 分隔,
):
s = """HST_9578_02_ACS_WFC_F775W 245.8976441 -26.5255957 4339.570 1882.364,
HST_10615_03_ACS_WFC_F435W 245.8976450 -26.5255138 2084.978 2101.122,
HST_10120_02_ACS_WFC_F658N 245.8976758 -26.5255024 1778.055 1752.193,
HST_10775_64_ACS_WFC_F606W 245.8977532 -26.5255296 2586.612 2603.519,
HST_10775_64_ACS_WFC_F814W 245.8977532 -26.5255296 2586.612 2603.519,
HST_9578_02_ACS_WFC_F775W 245.8978148 -26.5255491 4328.571 1885.712,
HST_10120_02_ACS_WFC_F625W 245.8978053 -26.5254741 1769.711 1754.229,
HST_10353_02_ACS_WFC_F435W 245.8976003 -26.5257784 3758.430 985.125,
HST_10775_64_ACS_WFC_F606W 245.8979115 -26.5254936 2576.410 2606.114
"""
bl = [[],[],[],[],[]]
for r in s.split(','):
for c in range(5):
bl[c].append(r.split()[c])
给出:
bl[0]
['HST_9578_02_ACS_WFC_F775W', 'HST_10615_03_ACS_WFC_F435W', 'HST_10120_02_ACS_WFC_F658N', 'HST_10775_64_ACS_WFC_F606W', 'HST_10775_64_ACS_WFC_F814W', 'HST_9578_02_ACS_WFC_F775W', 'HST_10120_02_ACS_WFC_F625W', 'HST_10353_02_ACS_WFC_F435W', 'HST_10775_64_ACS_WFC_F606W']
bl[1]
['245.8976441', '245.897645', '245.8976758', '245.8977532', '245.8977532', '245.8978148', '245.8978053', '245.8976003', '245.8979115']
bl[2]
['-26.5255957', '-26.5255138', '-26.5255024', '-26.5255296', '-26.5255296', '-26.5255491', '-26.5254741', '-26.5257784', '-26.5254936']
bl[3]
['4339.57', '2084.978', '1778.055', '2586.612', '2586.612', '4328.571', '1769.711', '3758.43', '2576.41']
bl[4]
['1882.364', '2101.122', '1752.193', '2603.519', '2603.519', '1885.712', '1754.229', '985.125', '2606.114']
编辑/更新:
将这两种方法合二为一:
import csv
with open('so.csv') as f:
bl = [[],[],[],[],[]]
reader = csv.reader(f)
for row in reader:
for col in range(5):
bl[col].append(row[col])
使用with
打开文件的好处是当你完成或发生异常时它会自动为你关闭。