file = open("byteS-F_FS_U.toff","r")
f = file.readline()
s = file.readline()
file.close()
f = int(f)
s = int(s)
u = s - f
file = open("bytesS-F_FS_U","w")
file.write(float(u) + 'n')
file.close()
当我运行代码时,它会这样说:
f file.write(float(u) + 'n') TypeError:
unsupported operand type(s) for +: 'float' and 'str'
我正试图从一个每隔几秒钟就会得到新号码的文件中加载号码。当它们被加载时,它们被减去并放入另一个文件中。我是一个新的python程序员。
首先,您需要放置要打开的文件的完整路径!
修复了第一件事后,我创建了一个循环程序,每10秒打开一次文件,并将结果写入另一个文件。处理异常,这样,如果另一个进程在打开/读取文件时正在写入文件,它就不会崩溃。Python 3语法。
import time
while True:
try:
file = open(r"fullpath_to_your_filebyteS-F_FS_U.toff","r")
f = int(file.readline())
s = int(file.readline())
file.close()
except Exception as e:
# file is been written to, not enough data, whatever: ignore (but print a message)
print("read issue "+str(e))
else:
u = s - f
file = open(r"fullpath_to_your_filebytesS-F_FS_U","w") # update the file with the new result
file.write(str(u) + 'n')
file.close()
time.sleep(10) # wait 10 seconds
你不能做float+字符串,那么你应该做smth,比如:
"{0}n".format(float(u))