-6

I am currently generating 8 random values each time I run a program on Python. These 8 values are different each time I run the program, and I would like to be able to now save these 8 values each time I run the program to a text file in 8 separate columns. When saving these values for future runs, though, I would like to still be able to keep previous values. For example: after run 1, the text file will be 8x1, after run 2, the text file will be 8x2, and after run n, the text file will be 8xn.

I have been looking at solutions like this: save output values in txt file in columns python

And it seems using 'a' instead 'w' will append my new values instead of overwriting previous values. I've been trying to follow the documentation on the method .write but just don't quite see how I can write to a particular column using this method. I have been able to simply write each column in its own text file, but I'd rather be able to write the columns together in the same text file for future runs I do with this program.

Edit: my outputs will be 8 floating point numbers and to reiterate, they will be random each time.

So after 1 run, I will create 8 floating point values: Run11, Run12, Run13, Run14, Run15, Run16, Run17, Run18. After my second run, I will create another set of values (8 entries long): Run21, Run22, Run23, Run24, Run25, Run26, Run27, Run28.

In the text file, I would like these values to be placed in specific columns like this: https://i.sstatic.net/tqUQI.jpg (this is what it would look like after 2 runs). The "Value n:" titles are the headers for each column.

9
  • can you add an example of your input and expected output Commented Jul 20, 2015 at 14:16
  • 1
    csv Commented Jul 20, 2015 at 14:19
  • My output will be 8 floating point numbers. I will edit my main question to include an example. Commented Jul 20, 2015 at 14:19
  • so you want to add a new column with 8 rows each time? Commented Jul 20, 2015 at 14:20
  • @PadraicCunningham: My guess is that Mathews24 simply wants a new row with 8 columns each time. Commented Jul 20, 2015 at 14:24

2 Answers 2

1
import csv
from tempfile import NamedTemporaryFile
from shutil import move
from itertools import chain
with open("in.csv") as f, NamedTemporaryFile(dir=".", delete=False) as temp:
    r = csv.reader(f)
    new = [9, 10, 11, 12, 13, 14, 15, 16]
    wr = csv.writer(temp)
    wr.writerows(zip(chain.from_iterable(r), new))

move(temp.name, "in.csv")

Input:

1
2
3
4
5
6
7
8

Output:

1,9
2,10
3,11
4,12
5,13
6,14
7,15
8,16

To take the header into account:

with open("in.csv") as f, NamedTemporaryFile(dir=".", delete=False) as temp:
    r = csv.reader(f)
    header = next(r)
    new = [9, 10, 11, 12, 13, 14, 15, 16]
    wr = csv.writer(temp)
    wr.writerow(header+["Value {}:".format(len(header)+1)])
    wr.writerows(zip(chain.from_iterable(r), new))
move(temp.name, "in.csv")

Input:

Value 1:
1
2
3
4
5
6
7
8

Output:

Value 1:,Value 2:
1,9
2,10
3,11
4,12
5,13
6,14
7,15
8,16

If you are adding an actual row each tie and not a column then just append:

with open("in.csv","a") as f:
    new = [9, 10, 11, 12, 13, 14, 15, 16]
    wr = csv.writer(f)
    wr.writerow(new)

Input:

value 1:,value 2:,value 3:,value 4:,value 5:,value 6:,value 7:,value 8:
1,2,3,4,5,6,7,8

Output:

value 1:,value 2:,value 3:,value 4:,value 5:,value 6:,value 7:,value 8:
1,2,3,4,5,6,7,8
9,10,11,12,13,14,15,16
Sign up to request clarification or add additional context in comments.

2 Comments

Nice. And it conforms to the OP's last comment. But not to the layout in imgur.com/zxoxaKM
@PM2Ring, I was actually going to mention the header as I did not see any but I will edit to account for it.
-1

what about

a = [1, 2, 3, 4, 5, 6, 7, 8]

f = open('myFile.txt', 'a')
for n in a:
    f.write('%d\t'%n)
f.write('\n')
f.close()

and you get as file content after running it 4 times

1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8

======= EDIT =========

Try this, its ugly but works ;-)

import os.path

h = ['Header 1', 'Hea 2', 'Header 3', 'Header    4', 'H 5', 'Header', 'Header 7', 'Header 8']
a = [1, 2, 3, 4, 5, 6, 7, 8]

fileName = 'myFile.txt'

#write header
withHeader = not os.path.isfile(fileName)

f = open(fileName, 'a')
if withHeader:
    print 'Writing header'
    for s in h:
        f.write('%s\t'%s)
    f.write('\n')

#write numbers
for i in range(0, len(a)):
    space = len(h[i])/2;
    n = a[i]
    for c in range(0, space):
        f.write(' ')
    print 'Writing %d'%n
    f.write('%d'%n)
    for c in range(0, space):
        f.write(' ')
    f.write('\t')
f.write('\n')
f.close()

result:

Header 1    Hea 2   Header 3    Header    4 H 5 Header  Header 7    Header 8    
    1         2         3            4       5     6        7           8       
    1         2         3            4       5     6        7           8       
    1         2         3            4       5     6        7           8       
    1         2         3            4       5     6        7           8       

2 Comments

Is there a good way to include headers for each column using this method, yet still being able to retrieve the values using np.loadtxt and not have the string headers interfere with this? @Danny
I used your original example and for future use of these values I just did: Value1,Value2,Value3,Value4,Value5,Value6,Value7,Value8 = np.loadtxt("path", skiprows = 1, unpack = True). Thank you for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.