Reputation: 9
I have a text file which consists of inputs:
1 2
3 4
5 6
7 8
I need result or output in the form of:
array_1 = [1, 3, 5, 7]
array_2 = [2, 4, 6, 8]
I have tried the below code:
arr=[]
f = open("file_path","r")
#read line into array
for line in f.read lines():
array_1 = arr.append(line.split()[0])
array_2 = arr.append(line.split()[1])
print(arr)
Upvotes: 0
Views: 941
Reputation: 4743
I would go with pandas package for processing such file.
You can then get the two arrays from columns the following way:
import pandas as pd
df = pd.read_csv("D:/tmp/file.csv",delimiter=" ", header=None)
array_1 = df[0].values
array_2 = df[1].values
And output would be:
>>> array_1
array([1, 3, 5, 7], dtype=int64)
>>> array_2
array([2, 4, 6, 8], dtype=int64)
Upvotes: 1
Reputation: 140168
Why are you appending and assigning the result? (which is None
). As a consequence, all numbers land in arr
and array_1
and array_2
are None
A few fixes:
append
directly on both lists, forget arr
like this:
array_1 = []
array_2 = []
f = open("file_path.txt","r")
#read line into array
for line in f.readlines():
array_1.append(int(line.split()[0]))
array_2.append(int(line.split()[1]))
now more pythonic:
readlines
, read line by linewith
block to open the file, so it's closed when exiting the blocklike this:
array_1 = []
array_2 = []
with open("file_path.txt") as f:
for line in f:
item1,item2 = map(int,line.split())
array_1.append(item1)
array_2.append(item2)
Upvotes: 1