-4

I have this function def to save some variable value I have add it manually by remote control of some E2 device

def saveKey(key):
     try:
         f=open("/etc/savekeys","w")
         f.write(str(key.replace("|", "")))
         f.close()
     except:
         pass

The value that save is like

7777776577777765

or

777AACD77777AACD

But every time I save a new value, the old value is deleted. I nedd to modify the def to make it save only 5 values, and when I save value number 6 it takes the place of number 1 and value number 7 takes the place of 2 and value number 8 takes the place of 3 ... etc ?!!

8
  • 6
    open with mode w will truncate the file. You may want to use a instead. Commented Mar 9, 2023 at 21:45
  • 4
    Why is "except: pass" a bad programming practice? Commented Mar 9, 2023 at 21:46
  • Does this answer your question? Open a text file without clearing everything in it? Commented Mar 9, 2023 at 21:47
  • But how I can make like like loop ?!! only 5 values and after that the new value place line number 1 and second new value place with line number 2 ...etc Commented Mar 9, 2023 at 21:59
  • 3
    How are you keeping track of what number value you are adding? If it's just based on the file itself, once it has five lines, you don't know which line was the most recently modified. Commented Mar 9, 2023 at 22:27

1 Answer 1

2

Some assumptions to be declared:

  • Age in the file is determined from the top down. The first line is the oldest, and the last line is the newest. Any new lines are always placed at the end of the file.
  • You're only writing one line at a time.
  • No threading or multiple processes are involved in this.

In this case, the flow is simple.

  • Open the file to get all lines.
  • Add your line.
  • If the number of lines exceeds your cap, then remove the first line.
  • Write all lines out.

The code looks like this:

def save_key(key, max_lines=5):
    lines = []
    with open("file", "r") as f:
        lines = f.readlines()

    lines.append(key)

    lines = lines[-max_lines:]

    with open("file", "w") as f:
        f.writelines(lines)
Sign up to request clarification or add additional context in comments.

3 Comments

I would use lines = lines[-max_lines:]. You don't even need the if statement before it if you do it that way.
This behavior makes more sense than what I think the asker described, but you should probably point out explicitly that it may be different. There's some ambiguity for sure, but it seems to me like the asker wanted the sixth value saved to go at the to of the file, taking the place of #1.
@CrazyChucky: I feel like this is stated in the assumption made; the first line is the oldest and the last line is the newest. I can make that a bit more explicit, though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.