0

Apologies if the question is hard to understand from the title but I'll try explain it in simple code.

numbers = []

for n in range(1,10):
  numbers.append(n)

print(numbers)

So obviously the above will print a list of numbers 1-9:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

But what if I want to save this output to be the input for 'numbers' for future runs? So that running it again will produce the following

[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
firex148
  • 1
  • 1
  • You need to store/preserve the list on the disk and load it next time you run the script – buran Nov 27 '22 at 19:45
  • Also https://stackoverflow.com/q/11218477/4046632 – buran Nov 27 '22 at 19:50
  • hi, solving your atual problem, you could try this: from os.path import exists file_path = 'list.txt' numbers = [] if exists(file_path): with open(file_path, 'r') as fp: for line in fp.readlines(): numbers.append(int(line[:-1])) for n in range(1,10): numbers.append(n) with open(file_path, 'w') as f: for i in numbers: f.write(f'{i}\n') print(numbers) – Andres Ospina Nov 27 '22 at 20:07
  • When you say "future runs" do you mean separate runs completely or do you mean later in the same run of the program? If the latter, then turn your loop into a function: `def append_numbers_list():` and call it like this: `append_numbers_list()`. Since `numbers` is global and you're modifying its value, it stays available for later use and modification in the same run of the program. By the way, you don't need the loop, you can do `numbers.append(list(range(1, 10)))` – Dennis Williamson Nov 27 '22 at 20:28

0 Answers0