如何使用python读取两列 [英] How to read two columns using python

查看:379
本文介绍了如何使用python读取两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何读取两列,第一列包含字母,第二列包含值.

How to read two columns the first of which contains letters and the second of the values.

C0      -0.158040
C1      -0.157117
C2      -0.143805
C3      -0.140561
S4      0.059175
H5      0.128940
H6      0.129007
H7      0.142421
H8      0.139979

我经常在下面使用此脚本(它适用于两列或更多列),但这次不可用!

I often used this script below (it works for two or more columns), but not for this time !!

with open('file.csv') as f:
    f=[x.strip() for x in f if x.strip()]
    data=[tuple(map(float,x.split())) for x in f[2:]]
    oX=[x[0] for x in data]
    oY=[x[1] for x in data]

感谢您的帮助.

推荐答案

这是另一种解决方案:

import csv

with open('file.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        res = row[0].split()
        oX = res[0]
        oY = res[1]
        print (oX, oY)

输出:

('C0', '-0.158040')
('C1', '-0.157117')
('C2', '-0.143805')
('C3', '-0.140561')
('S4', '0.059175')
('H5', '0.128940')
('H6', '0.129007')
('H7', '0.142421')
('H8', '0.139979')

这篇关于如何使用python读取两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆