I have a numbers.txt file that consists of several 100K lines, each one made up of two unique digits separated with : sign:
407597693:1604722326.2426915
510905857:1604722326.2696202
76792361:1604722331.120079
112854912:1604722333.4496727
470822611:1604722335.283259
My goal is to locate a line with the number 407597693 on the left side and then proceed to change the number on the right side by adding 3600 to it. After that, I have to rewrite the numbers.txt file with all the changes. I must perform the same (just different number) operation on the same txt file as fast as possible.
I have managed to make it work via with open: file operations and for loop for each line, searching for the needed number, modifying the line, and then rewriting the whole file. However, I've noticed that constantly performing such an operation does take some time for my program, about 0.2-0.5 sec, which adds up over time and slows everything down considerably.
Here is the code I am using:
number = 407597693
with open("numbers.txt", "r+") as library:
file = library.read()
if (str(number) + ":") in file:
lines = file.splitlines()
with open("numbers_temp.txt", "a+") as library_temp:
for line in lines:
if (str(number) + ":") in line:
library_temp.write(
"\n" + str(number) + ":" + str(time.time() + 3600)
)
else:
library_temp.write("\n" + line)
library_temp.seek(0)
new_file = library_temp.read()
with open("numbers.txt", "w+") as library_2:
library_2.write(new_file)
os.remove("numbers_temp.txt")
I would really appreciate any input on how to speed up this process, many thanks in advance!