Search code examples
pythonincrement

Problem with incrementing the value of a variable between several runs of the program


See the following code:

def increment():
    x = 0
    file = open(f'file{x}.txt', 'a')
    file.write("something...")
    file.close()
    x = x + 1

You might have figured out what, I'm trying to do here. But the problem is, each time I run the program the value of x is set to 0 and every time it's opening the file, file1.txt, I even tried this code:

x = 0
def increment():
    file = open(f'file{x}.txt', 'a')
    file.write("something...")
    file.close()
    x = x + 1

Assigning the value outside the function, but still the same problem. I want it to open files like this:
First Run: file1.txt,
Second Run: file2.txt,
Third Run: file3.txt and so on...
But it's always opening the file, file1.txt.


Solution

  • variables are stored in memory, not hard drive. whenever your program ends and the process terminates, Python will automatically remove all the references to created objects in memory therefore all the objects will go...

    In order to do that, you have 2 choices:

    solution 1:

    you need to somehow store that number in hard drive. May be in a separate text file. Then whenever you want to create new files, first read that file and get that number from it. Do your job and at the end do not forget to write it back.

    like:

    # getting the number (assumed this file is already present
    # and has the first line filled with a number)
    with open("read_number.txt") as f:
        x = int(f.read())
    
    with open(f"file{x}.txt", 'a') as f:
        f.write("something\n")
    
    with open("read_number.txt", 'w') as f:
        x += 1
        f.write(str(x))
    

    solution 2:

    Another solution is whenever you want to create a new file, search the directory , get all the names(with os.listdir) and sort them. Then you can get the last name and can easily increment it by one.

    something like:

    import os
    import re
    
    lst = [i for i in os.listdir() if i.startswith("file")]
    lst.sort(key=lambda x: int(re.search(r'\d+', x).group()))
    print(lst)
    

    You can do this in many ways I just intended to show you the path.