0

I need to write a python script to iterate calculations on several instances, unfortunately the last test overwrites all those before.

Do you know a way to avoid this? Here is my code, thank you!

import subprocess
import os
from os import listdir
from os.path import isfile, join
import sys


files = [f for f in listdir("data/dataAlea2_50") if isfile(join("data/dataAlea2_50", f))]
K = [2,5]

commande = "g++ -std=c++11 *.cpp -o main -Wall"


subprocess.getoutput(commande)

for file in files:
    for k in K:


        tmp = subprocess.getoutput("./main" +" " + str(k) + " data/dataAlea2_50/"+ file)
        f = open("resulat.txt","w+")
        f.write("Voici les resultats pour k = " + str(k) + " et pour les données :" + file )
        f.write(tmp)


f.close()
LeMage
  • 5
  • 1
  • 4

2 Answers2

2

Use open mode a:

f = open("resulat.txt", "a")

Unless you’re also reading from f, there is no need to specify + in the open mode.

Better yet, use a with statement to open the file.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

You want to append instead of write. For example:

import subprocess
import os
from os import listdir
from os.path import isfile, join
import sys


files = [f for f in listdir("data/dataAlea2_50") if isfile(join("data/dataAlea2_50", f))]
K = [2,5]

commande = "g++ -std=c++11 *.cpp -o main -Wall"


subprocess.getoutput(commande)

for file in files:
    for k in K:


        tmp = subprocess.getoutput("./main" +" " + str(k) + " data/dataAlea2_50/"+ file)
        with open("resulat.txt", "a") as f:
            f.write("Voici les resultats pour k = " + str(k) + " et pour les données :" + file )
            f.write(tmp)

where the important piece is using the "a" option instead of "w+" for the open function. You can find the full list of options here

wogsland
  • 9,106
  • 19
  • 57
  • 93