How to import .txt file into python

20,400

Solution 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]

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
Share:
20,400

Related videos on Youtube

Ankit Chaurasia
Author by

Ankit Chaurasia

Updated on August 11, 2020

Comments

  • Ankit Chaurasia
    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 array array2.

Related