How to import .txt file into python
20,400
Solution 1
You just have to:
-
open()
file in read-only mode -
read()
each line -
for
each line in file-
split()
each line at,
-
append()
first part toarray1
and second part toarray2
- 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]
Solution 2
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()])
Solution 3
You could use numpy:
my_data = np.loadtxt('poo.txt', delimiter=",", unpack=True)
list1, list2 = my_data[::] #unpack your array
Related videos on Youtube

Author by
Ankit Chaurasia
Updated on August 11, 2020Comments
-
Ankit Chaurasia over 2 years
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 arrayarray2
.