0

There is an input file "input.txt". It looks like:

7
4
2
5
2
9
8
6
10
8
4

And there's a code:

inn = open("/storage/emulated/0/input.txt", "r")
a = 0
b = 10
array = []

while not a == b:
     for i, line in enumerate(inn):
         if i == a:
              array += str(line)
     a+=1
print(array)

I need to put all the numbers in "array" variable, but wher I run the code -- I get empty "array". Is there a mistake in a code?

(sorry for such noob question)

maxpushka
  • 13
  • 2

1 Answers1

1

I can't reproduce your error. Also, I don't get an empty array when running your code. See the following code and the results. I still suggest using np.genfromtxt when the input data is as clean as yours.

Code:

import numpy as np

# I have input.txt in same directory as this .py-file

# np.genfromtxt with int and with string
approach1a = np.genfromtxt('input.txt', dtype=int)
approach1b = np.genfromtxt('input.txt', dtype=np.str_)

# list comprehension
approach2 = []
with open('input.txt') as file:
    approach2 = [str(line) for line in file]

# like your approach, but without a, b and the if statement
approach3 = []
with open('input.txt') as file:
    for line in file:
        approach3.append(line)

# your code
inn = open("input.txt", "r")
a = 0
b = 10
array = []
while not a == b:
    for i, line in enumerate(inn):
        if i == a:
            array += str(line)
    a+=1

Results:

>>> approach1a
array([ 7,  4,  2,  5,  2,  9,  8,  6, 10,  8,  4])
>>> approach1b
array(['7', '4', '2', '5', '2', '9', '8', '6', '10', '8', '4'],
      dtype='<U2')
>>> approach2
['7\n', '4\n', '2\n', '5\n', '2\n', '9\n', '8\n', '6\n', '10\n', '8\n', '4']
>>> approach3
['7\n', '4\n', '2\n', '5\n', '2\n', '9\n', '8\n', '6\n', '10\n', '8\n', '4']
>>> array
['7', '\n']

The reason that only the first line of the inpur file is read with your code is because with open you can only iterate over the lines once. If you have done that, you can't go back. To understand that, see for example @Aaron Hall's anwer to this question: there is only a method next, but there is no way to go back (in this case to go back a line). You have reached that point where all lines of open were used once when you set the value of a to 1, i.e. after you have added the first line of the input file to array. This is why I understand that your code only reads the first line, why I can't reproduce you claiming you have array as an empty list and why I suggested approach3.

Michael H.
  • 3,323
  • 2
  • 23
  • 31