我已经为我过去几天的许多问题找到了解决方案,但还需要一个解决方案。
我将使用Python脚本从TXT文件中读取,分开项目,添加时间,并另存为另一个TXT文件。
问题是Python继续读取第一行并且仅使用TXT文件中的第一行。
我的带有数据的txt文件如下:
T: 55% 24.50 12% 90% N
T: 55% 25.50 12% 90% N
T: 55% 26.50 12% 90% N
T: 55% 27.50 12% 90% N
我的新txt文件如下:
2013-05-10 21:42:13 24.50
2013-05-10 21:42:14 24.50
虽然看起来像:
2013-05-10 21:42:13 24.50
2013-05-10 21:42:14 25.50
你能帮我编辑我的脚本,设置Python脚本只读最后一行来自txt文件,单独的项目,添加时间并将它们保存到新的txt文件中吗?
我的脚本如下:
#!/usr/bin/python
import time
buffer = bytes()
f = open("arduino.txt")
while buffer.count('T:') < 2:
buffer += f.read(30)
f.close();
# Now we have at least one complete datum. Isolate it.
start = buffer.index('T:')
end = buffer.index('T:', start+1)
items = buffer[start:end].strip().split()
print time.strftime("%Y-%m-%d %H:%M:%S"), items[2]
最好的问候。
答案 0 :(得分:1)
您可以阅读最后一行:
fh = open("arduino.txt")
for line in fh:
pass
last = line
现在,
#You might want to split based on specific delimiters, but I am using the default
split_line = last.split() #T: 55% 27.50 12% 90% N
现在,打开另一个文件,然后保存内容
#!/usr/bin/python
import time
f = open("arduino.txt")
while line in f:
pass
f.close();
#line is the last line now
items = line.strip().split()
print time.strftime("%Y-%m-%d %H:%M:%S"), items[2]
#Write to the new file here.