There simply isn’t a “better” way than yours, it works the way it was supposed, it is easy to read, etc. However, if you classify speed as “better,” small adjustments can be made for sure.
I didn't know much about this speed in Python, but here are a few suggestions that work only under certain conditions. I hope someone else comes up with something better, maybe this answer will help them.
If the file will not contain lines such as
\n
but instead only \n , then this path will be noticeably faster:
def send(self, queue, fd): for line in fd: if line != '\n': queue.write(json.loads(line.strip()))
Time Values:
using: strip() :: 1.8722578811916337 using: line != '\n' :: 1.0126976271093881 using: line != '\n' and line != ' \n' :: 1.2862439244170275
Please note, however, that this may become even slower if there is no single line \n in the file, I confined it to fd as ["string", "\n", "test string", "\n", "moreeee", "\n", "An other element"]
You probably don't know if the lines are only \n , however .strip() is pretty slow, so there might be more efficient ways.
user1632861
source share