Question

I have made an executable script in Python which takes as a command line argument the name of a file. The script runs and outputs a number. I have several files for which I have to run the script and I want to store all the results in a separate file called results.txt. The file should look like this:

name_of_file_1 result_number_1
name_of_file_2 result_number_2
name_of_file_3 result_number_3
...
name_of_file_n result_number_n

This is what I tried so far, but every time the name of the file and the result are overwritten.

args = sys.argv[1]
f = open('results.txt', 'w')
f.write(args + " " + str(len(i)) + "\n")
f.close()

How can I do this?

Was it helpful?

Solution

You can use the append mode instead of the write mode as follows:

f = open('results.txt', 'a')
f.write(args + " " + str(len(i)) + "\n")
f.close()

The append mode adds on to the existing file whereas the write mode simply clears the file or overwrites it.

OTHER TIPS

Use:

f = open('results.txt', 'a')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top