我有这个奇怪的格式化文本文件我试图读入,我不知道如何告诉python每行以分隔符开头。
文本文件中的一行如下所示:
3.146 -1.339 .358 29.214
该文件使用5个空格作为分隔符。如何将每行读入包含4个项目的列表?
答案 0 :(得分:3)
您可以使用以下内容将每行读入包含4个项目的列表中:
with open(filename, 'r') as f:
# this will read in each row as:
#
# ['3.146', '-1.339', '.358', '29.214']
#
# so `lines` will contain
#
# [['3.146', '-1.339', '.358', '29.214'], ...]
lines = map(str.split, f.readlines())
# or alternatively, as @jez mentioned, it may be more readable to use
lines = [ line.split() for line in lines ]
# you'll then likely want to convert them to floats
#
# this will give you:
#
# [[3.146, -1.339, 0.358, 29.214], ...]
data = [ map(float, split_line) for split_line in lines ]
答案 1 :(得分:1)
使用split
结合strip
删除多余的空格:
my_file_data = " 3.146 -1.339 .358 29.214"
data = my_file_data.strip().split(' ')
# do stuff with your data
print(data[0])
答案 2 :(得分:0)
这是你的分隔符:
delimiter=' '
然后,您只需使用分隔符
分割您的文本行 lineoftext.split(delimiter)