-2

I have build a code that does the following:

#code is supposed to access servers about 20 of them
#server details are in 'CheckFolders.ini'
# retrieve size, file numbers and number of folders information
# put all that in a file CheckFoldersResult.txt

Need to find out how can i write to CheckFoldersResult.txt so that the latest results are appended starting from the beginning of the file instead of appending at end of the existing text.

1 Answers1

0

I'd read the results, insert the lines I want at the top, then overwrite the file like so:

def update_file(filepath, new_lines):
    lines = []
    with open(filepath, 'r') as f:
        lines = f.readlines()
    rev_lines = reversed(new_lines)
    for line in rev_lines:
        lines.insert(0, line)
    with open(filepath, 'w') as f:
        f.writelines(lines)
dsillman2000
  • 976
  • 1
  • 8
  • 20
  • I don't quite get why this is accumulating *all* lines in-memory first, and using a rather inefficient insert-0 to boot. Why not ``f.writelines(new_lines)`` and then ``f.writelines(lines)`` *without* merging ``new_lines`` and ``lines``? – MisterMiyagi Oct 28 '21 at 16:59