Python读取.txt文件->列表 [英] Python read .txt File -> list
问题描述
我有一个.txt文件,我想获取列表中的值.txt文件的格式应为:
I have a .txt File and I want to get the values in a list. The format of the txt file should be:
value0,timestamp0
value1,timestamp1
...
...
...
最后,我想获得一个带有
In the end I want to get a list with
[[value0,timestamp0],[value1,timestamp1],.....]
我知道很容易获得这些值
I know it's easy to get these values by
direction = []
for line in open(filename):
direction,t = line.strip().split(',')
direction = float(direction)
t = long(t)
direction.append([direction,t])
return direction
但是我有一个大问题:创建数据时,我忘记在每一行中插入一个"\ n".
But I have a big problem: When creating the data I forgot to insert a "\n" in each row.
这就是为什么我使用这种格式:
Thats why I have this format:
value0, timestamp0value1,timestamp1value2,timestamp2value3.....
每个时间戳记都有13个字符.
Every timestamp has exactly 13 characters.
是否可以根据需要在列表中获取这些数据?再次获取数据将是很多工作.
Is there a way to get these data in a list as I want it? Would be very much work get the data again.
谢谢最高
推荐答案
我使用您的示例编码了一个快捷方式,而不是使用13,而是使用len("timestamp"),以便您可以适应
I coded a quickie using your example, and not using 13 but len("timestamp") so you can adapt
instr = "value,timestampvalue2,timestampvalue3,timestampvalue4,timestamp"
previous_i = 0
for i,c in enumerate(instr):
if c==",":
next_i = i+len("timestamp")+1
print(instr[previous_i:next_i])
previous_i = next_i
输出已解密:
value,timestamp
value2,timestamp
value3,timestamp
value4,timestamp
这篇关于Python读取.txt文件->列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!