2

I have a text file with many values like

2.81,5.62
7.14,8.00
2.72,5.44
3.87,7.74
1.90,3.80
7.82,8.00
7.02,8.00
5.50,8.00
9.15,8.00
4.87,8.00
8.08,8.00
5.58,8.00
9.13,8.00

Now I need to read these values as I want to put the first value into an array array1 and then the second value in an array array2.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Ankit Chaurasia
  • 163
  • 2
  • 5
  • 14
  • Possible duplicate of [How do I read a file line-by-line into a list?](http://stackoverflow.com/questions/3277503/how-do-i-read-a-file-line-by-line-into-a-list) – Aman Jaiswal Mar 24 '17 at 19:56

3 Answers3

3

You can use readlines() to read all the lines, and then split each line by the , character:

f = open('numbers.txt', 'r')
list1, list2 = zip(*[x.split(',') for x in f.readlines()])
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

You just have to:

  1. open() file in read-only mode
  2. read() each line
  3. for each line in file
    1. split() each line at ,
    2. append() first part to array1 and second part to array2
    3. done

Code:

array1 = []
array2 = []

with open('filename.txt', 'r') as f:
    for line in f.readlines():
        l = line.strip().split(',')
        array1 = l[0]
        array2 = l[1]
dot.Py
  • 5,007
  • 5
  • 31
  • 52
1

You could use numpy:

my_data = np.loadtxt('poo.txt', delimiter=",", unpack=True)
list1, list2 = my_data[::] #unpack your array
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69