-1

I am trying to store my run time output into a CSV file. It stores only one data, but I want to store all of them.

My code,

path = self.paths[src][dst]
next_hop = path[path.index(dpid) + 1]
out_port = self.network[dpid][next_hop]['port']

print("path: ", path)
writer=csv.writer(open('pth.csv','wb'))
writer.writerow([path]);

The output is,

['62:61:5f:80:dc:ca', 5, 4, 1, '46:22:26:36:96:48']
['62:61:5f:80:dc:ca', 5, 4, 1, '46:22:26:36:96:48']
['62:61:5f:80:dc:ca', 5, 4, 1, '46:22:26:36:96:48']
['62:61:5f:80:dc:ca', 5, 4, 1, '46:22:26:36:96:48']
['62:61:5f:80:dc:ca', 5, 4, 1, '46:22:26:36:96:48']
['46:22:26:36:96:48', 1, 4, 5, '62:61:5f:80:dc:ca']
['46:22:26:36:96:48', 1, 4, 5, '62:61:5f:80:dc:ca']
['46:22:26:36:96:48', 1, 4, 5, '62:61:5f:80:dc:ca']

It would be helpful if you could give a hint

joes
  • 1
  • 3
  • 1
    I see multiple different lines in the output. Please explain how this is only "one data" and what "all of them" would look like. – mkrieger1 Feb 12 '19 at 10:15
  • The multiple different lines are the actual output. But in the file, it stores only the last line data. – joes Feb 12 '19 at 10:19

1 Answers1

1

But in the file, it stores only the last line data.

It's probably because of this:

open('pth.csv','wb')

By using w, you truncate the file, meaning it will overwrite the previous contents.
See https://docs.python.org/2/library/functions.html#open:

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position).

See also related How do you append to a file in Python?.

Try using a:

open('pth.csv','ab')
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • Thanks, it works well. But it also keeps the previous data. is it possible to keep the current data only? – joes Feb 12 '19 at 10:56
  • @joes Hmm.. I don't understand what you mean.. You can either keep appending (`a`) or always overwrite what's already there (`w`). Other than that, you'll have to maybe use some other [file seeking](https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects) methods to "restart" the file pointer. Something like, use `a` until you've written 10 rows. Then seek back to the start, then write the next 10 rows (overwriting the "previous" data). – Gino Mempin Feb 12 '19 at 12:25
  • @joes ..or maybe keep appending (`a`) the "current data", then for a new data set, `open` a new file or move/rename the current file. It's quite unclear what you want, since all you asked is "_but I want to store all of them_". – Gino Mempin Feb 12 '19 at 13:03