【发布时间】:2013-09-22 07:26:42
【问题描述】:
我编写此代码是为了读取一个文件,因为它正在被写入通过切换游戏中的开关来控制灯。该开关会导致将字符串附加到文件中。该程序有效,但速度很慢。它读取的文件有超过 15k 行要迭代,因此只能每隔一秒左右更新一次。有没有办法加快速度?谢谢!
import serial
s = serial.Serial(port = "COM3", baudrate = 9600)
def file_len():
try:
with open("file", "r") as f:
for r, l in enumerate(f):
pass
return r + 1
except:
pass
def toggle(data, value):
if(data.find("Clap Off!") == 0 and value == True):
print("Off")
s.write("RelayOff")
elif(data.find("Clap On!") == 0 and value == False):
print("On")
s.write("RelayOn")
truth = False
while True:
try:
file = open("file", "r")
for i, line in enumerate(file):
if i == (file_len() - 2):
toggle(data = file.readline(), value = truth)
truth = not truth
file.close()
except:
pass
编辑: 我尝试使用以下方法绕过 while file_len 函数:
while True:
try:
file = open("file", "r")
file.seek(-1, 2)
#print(file.readline())
toggle(data = file.readline(), value = truth)
file.close()
truth = not truth
except:
pass
但它会引发错误“io.UnsupportedOperation: can't do nonzero end-relative seeks” 这只是 seek() 的工作方式,还是有办法从文件末尾向后搜索?
【问题讨论】:
-
您的
s.write()不包含换行符;与print()不同,使用file.write()不会自动添加\n。您的数据在最后一行被连接起来。 -
这个问题的全部目的是找出如何避免遍历整个文件,而只是针对 EOF 之前的行。
-
公平点;我敢肯定,这里还有其他重复项。撤回了我提议的欺骗。
-
快速仅供参考,如果
file.seek(n, 2)相对于文件末尾是n,则 -1 表示超出文件末尾。您想改为尝试 0。
标签: python file-io python-3.x