0

I'm trying to create a random list of integers; but this list should be held constant once generated, rather than being generated anew every time I run the program. To do so, my idea is to generate it once, write it to a file, comment out that part, then read it back everytime I use it.

Unfortunately, I can't get reading & writing integers to work. Here's the simplest way to exhibit the problem.

I first write a list of integers as follows

learning=[]
for i in range(20):
    learning.append(i)
np.savetxt('learning.txt',learning)

This does create the txt file and populate it with numbers; but they appear as 0.00000000000e+00, 1.000000000000e+00, etc. Writing learning.append(int(i)) instead doesn't help.

I then comment out the above block and attempt to read back the numbers

l=open('learning.txt','r')
learning=[]
for line in l:
    print line.rstrip('\n')

This returns the list of numbers, but in the form 0.000000000e+00, 1.000000000e+00, etc, whereas I wanted them as integers.

If I instead type print int(line.rstrip('\n')), I get the error message invalid literal for int() with base 10: '0.0000000000000e+00'

Alec
  • 8,529
  • 8
  • 37
  • 63
J.D.
  • 139
  • 4
  • 14
  • If you are not fixated on the writing to a file approach, I would suggest using a fixed seed value. This will ensure same random numbers being generated every time. Have a look: https://stackoverflow.com/questions/22639587/random-seed-what-does-it-do – razdi Apr 26 '19 at 02:40

4 Answers4

0

In you really wanted to use NumPy, specify the format:

learning = list(range(10))
np.savetxt('learning.txt', learning, fmt='%d')

However, these tasks can easily be done without NumPy:

learning = list(range(10))
with open('learning.txt', 'w') as outfile:
    outfile.write('\n'.join([str(i) for i in learning]))

To load back:

with open('learning.txt', 'r') as infile:
    list_of_numbers = [int(i) for i in infile]

You may want to look into using a seed for your random number generator as well to avoid having to save to a file.

iz_
  • 15,923
  • 3
  • 25
  • 40
0

If you are using Numpy then you would need to specify the format to make integer output:

np.savetxt(filename, array, fmt=“%d”)
drclaw
  • 2,463
  • 9
  • 23
0

Have you tried to write a text file with this?

learning = [i for i in range(20)]

try:
    with open('learning.text', 'w') as f:
        for i in learning:
            f.write('{}\n'.format(i))

    print('Done')

except Exception as e:
    print('Error: {}'.format(e))

And I tried to create a function for reading, it works fine

def read_text(file_name):
    my_res = []
    try:
        with open('{}'.format(file_name), 'r') as f:
            for i in f:
                my_res.append(i.rstrip('\n'))

        print('Read successfully')

    except Exception as e:
        print('Error: {}'.format(e))

    return list(map(lambda i: int(i), my_res))

Here's my full example

learning = [i for i in range(20)]

def create_text(mylist):
    try:
        with open('learning.text', 'w') as f:
            for i in learning:
                f.write('{}\n'.format(i))

        print('Text created')

    except Exception as e:
        print('Error: {}'.format(e))

    return None


def read_text(file_name):
    my_res = []
    try:
        with open('{}'.format(file_name), 'r') as f:
            for i in f:
                my_res.append(i.rstrip('\n'))

        print('Read successfully')

    except Exception as e:
        print('Error: {}'.format(e))

    return list(map(lambda i: int(i), my_res))


test = read_text('learning.text')

print(test)

My result

Read successfully
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
N. Arunoprayoch
  • 922
  • 12
  • 20
0

You can save text using integer formatting:

np.savetxt(filename, array, fmt=“%i”)
Alec
  • 8,529
  • 8
  • 37
  • 63
  • Hi. Thanks, that's the quickest fix. As a follow up though... Why does ``` print 2 in learning ``` return False? (2 is the first number that appears when I type print learning) – J.D. Apr 26 '19 at 03:10
  • To answer your question, `2 in learning` is false if the value `2` doesn't appear in `learning` (`learning` is a list) – Alec Apr 26 '19 at 03:16
  • Hi, 2 does appear in learning. When I enter print learning, I get a list that starts with [2,3,5,6,...] So print 2 in learning should yield True. Why does it say False? – J.D. Apr 26 '19 at 03:26
  • ['2','3','5','6','8','11','12','14','15','16', … (goes on a for a long time)] (I went back and changed the code for writing learning.txt to what I was really interested in.) – J.D. Apr 26 '19 at 03:36
  • Those are strings, not integers. If '2' in learning will return True – Alec Apr 26 '19 at 03:36
  • I got it now. This time, learning.append(int(line.rstrip('\n'))) works Thanks – J.D. Apr 26 '19 at 03:40