Search code examples
pythonpython-2.7callfile-writingfile-read

The String is Not Read Fully


I wrote a programme to generate a string of number, consisting of 0,1,2,and 3 with the length s and write the output in decode.txt file. Below is the code :

import numpy as np

n_one =int(input('Insert the amount of 1: '))
n_two =int(input('Insert the amount of 2: '))
n_three = int(input('Insert the amount of 3: '))
l = n_one+n_two+n_three
n_zero = l+1
s = (2*(n_zero))-1


data = [0]*n_zero + [1]*n_one + [2]*n_two + [3]*n_three
print ("Data string length is %d"  % len(data))

while data[0] == 0 and data[s-1]!=0:
         np.random.shuffle(data)
datastring = ''.join(map(str, data))
datastring = str(int(datastring))
files = open('decode.txt', 'w')
files.write(datastring)
files.close()
print("Data string is : %s " % datastring)

The problem occur when I try to read the file from another program, the program don't call the last value of the string.

For example, if the string generated is 30112030000 , the other program will only call 3011203000, means the last 0 is not called.

But if I key in 30112030000 directly to the .txt file, all value is read. I can't figure out where is wrong in my code.

Thank you


Solution

  • Some programs might not like the fact that the file doesn't end with a newline. Try adding files.write('\n') before you close it.