3 回答
TA贡献1817条经验 获得超6个赞
不要一次性读取整个文件,请按行读取,然后拆分:
with open(filepath) as f:
for line in f:
print line.strip().split(',')
您也可以先在换行符上分割,然后在逗号处循环并分割:
lines = [line.split(',') for line in somestring.splitlines()]
但是对于逗号分隔的文件,最好的选择是使用csv模块:
import csv
with open(filepath, 'rb') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
print row
这为您提供了以下行:
['States', ' Total Score', ' Critical Reading', ' Mathematics', ' Writing', ' Participation (%)']
['Washington', '1564', '524', '532', '508', '41.2000']
['NewHampshire', '1554', '520', '524', '510', '64.0000']
由于第一行带有标题,因此您也可以使用aDictReader并获取将标题映射到值的字典:
with open(filepath, 'rb') as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
print row
# address columns as: row['States'], row['Total Score']
将行输出为:
{' Writing': '508', ' Total Score': '1564', ' Critical Reading': '524', 'States': 'Washington', ' Mathematics': '532', ' Participation (%)': '41.2000'}
TA贡献1828条经验 获得超4个赞
有re.split多个字符拆分:
import re
re.split("\n| ","this is\na short\ntest...")
>>> ['this', 'is', 'a', 'short', 'test...']
添加回答
举报