I am attempting to write to a text file in specific positions based on text in the file. For example, a file may have the following lines:
user=dog:admin
user=cat:admin
user=giraffe:admin
user=elephant:moderator
user=bat:moderator
user=snake:moderator
A way to parse that is to open with the following code and write between them:
with open("testfile", "r+") as testfile:
lines = testfile.readlines() #read lines into list from file
testfile.truncate() #empty file of data
role_index = [i for i, line in enumerate(lines) if 'moderator' in line][0] #find first instance where moderator appears
lines.insert(role_index, 'user=dragon:moderator\n') #insert our new user into that position with a newline
for line in lines:
testfile.write(line) #write back into empty file and fill with our user list
The file I work with has the potential to grow to a size to be much too large to parse efficiently by that manner above. What I'm seeking is a way to read through the file line by line (in a CPU efficient manner, e.g. reading every line super fast in a massive log takes a toll on the CPU) without instituting a sleep call to preserve CPU resources and a way to preserve memory.
If there's a way to pull that off, that would make my day.