0

I am using Python to create a text file with some text inside.

I need these files to stay saved, but have the same name at the same time, since currently, Python overwrites the old text file with the same name, and the old data gets deleted.

I have tried using os.rename(f"file_name_x.txt), where x is a number that is incremented each time. This did not work as the program restarts and x is declared as the same old integer and the file is replaced again.

The intended result is to have something like this:

file_name_1.txt

file_name_2.txt

file_name_3.txt

...

I'm still trying new methods after posting this but if someone knows a workaround to this, it would be great

Jakub Zak
  • 35
  • 6
  • I have tried splitting the old text files, finding the number of that text file and using it to determine the next number however this did not work – Jakub Zak Apr 26 '22 at 13:28
  • You can write to the file without overwritting it with parameter `"a"`. It is not your exact question but I felt like this whole process was a workaround for that. – Titouan L Apr 26 '22 at 13:30
  • "I have tried (...) however this did not work" - please show us what you tried – h4z3 Apr 26 '22 at 13:31
  • I have also tried doing something like `f"file_name_{x}.txt` and that helps with adding the integers into the name of the file but i still cant find a good way to increment them – Jakub Zak Apr 26 '22 at 13:33
  • 1
    Does this answer your question? [Create file but if name exists add number](https://stackoverflow.com/questions/13852700/create-file-but-if-name-exists-add-number) – Pranav Hosangadi Apr 26 '22 at 13:33
  • @PranavHosangadi yes! thank you so much, ive been working on this for hours, and it finally works! – Jakub Zak Apr 26 '22 at 13:41

1 Answers1

0

The first idea coming to mind would be to use a json file and putting the text in there, where the keys are integers and values are the strings. Otherwise, you would need to get all the filenames. Find the one with the largest index, reverse iterate through all the indicies using for idx in range(maxIdx,0,-1) and os renaming them to the same name with the index+1. Im on my phone right now so i wont be able to code that out for you, but it seems you should be capable to do that yourself anyways.

NoBlockhit
  • 369
  • 2
  • 15