0

I want to overwrite a file in order to change a certain line. The only code I have come up with is as follows:

import os

def update(fil, argument, line):
    z = fil.name
    k = fil.readlines()
    k[line] = argument
    m = file.open("test.txt")
    for e in k:
        m.write(str(e))
    os.remove(fil)
    m.name = z

The function goes as follows: I have three parameters:

  • the file I want to overwrite
  • the argument I want to write
  • the line the argument goes at.

Then, I store the name and the lines of the file in two variables, z and k, I say that the (line)th element of k is the argument. After that, I create a new file, write k into it, delete the first file and change the name of the new file to z.

I haven't programmed in Python in a long time, so all help will be greatly welcome!

Alejandro Galera
  • 3,445
  • 3
  • 24
  • 42
Phazoning
  • 51
  • 5
  • It isn't clear what you are trying to do. Are you trying to overwrite a file, or just replace a single line in the file? – samfrances Apr 25 '18 at 08:19
  • I'm triying to replace a single line, but I haven't been able to do this w/o overwriting the whole file. I'm quite frustrated about it tbh – Phazoning Apr 25 '18 at 08:46
  • Well, you could memory map it. But overwriting a file to change a line is common practice. The "problem" is that files are not line based anyway, so to change just a line, the new line would have to be exactly the same length for it work. – Prof. Falken Apr 25 '18 at 09:14
  • Just a dinausaur remark: it is no use loading the file in memory. It doesn't speed up anything and just wastes memory. – Serge Ballesta Apr 25 '18 at 09:28
  • Prof. Falken, I'm afraid I cannot do so, for the use I intend for the file is to serve as a memory so, apart from some common elements, lines are to be different one from another. Serge Ballesta, thanks for the tip, I haven't programmed in a while and I'm a bit lost, so it'll take a while for me to get used to it again – Phazoning Apr 25 '18 at 10:16
  • @SergeBallesta, I didn't mean read it into memory, I meant memory map it. But for small files, i.e. less than megabytes, none of that matters, it's going to be fast no matter what you do. – Prof. Falken Apr 25 '18 at 11:08
  • 1
    @Prof.Falken: OP's code loads the whole file in memory, at the `fil.readlines()` call. – Serge Ballesta Apr 25 '18 at 11:14
  • https://stackoverflow.com/questions/8037070/whats-the-fastest-way-to-read-a-text-file-line-by-line#8037093 – Prof. Falken Apr 25 '18 at 11:23

0 Answers0