-2

I´m new in reading text files using python. I need to read a file which have in each line 4 data that I need, here is my text file

1 -10 0 0    
2 -10 -10 0    
3 0 -10 0    
4 10 -10 0    
5 10 0 0    
6 0 0 0

my problem is, that if I use read().splitlines(), it only creates a vector with each line, but I need a vector only for the first column, one for the second, one for the third, and also one for the fourth column. Con anyone help me please?

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
j.p
  • 13
  • 2
  • look [here](http://stackoverflow.com/questions/16503560/read-specific-columns-from-a-csv-file-with-csv-module) and [here](http://stackoverflow.com/questions/5741518/reading-each-column-from-csv-file). – bunji Jan 27 '17 at 19:33
  • do you mean you need a vector for each column? example [1,2,3,4,5,6] , [-10,-10,0,10,10,0] – Md Sifatul Islam Jan 27 '17 at 19:34

2 Answers2

0

Try this. It open the file for reading as the file pointer fp. It looks at each line, one at a time, removes the newline characters, splits the line into a list on the space character, then converts each element in the list to an integer. In then forms a list of all of the lists of integers and stores it as the variable data.

with open('filename.txt', 'r') as fp:
    data = [list(map(int, line.strip().split(' '))) for line in fp]
James
  • 32,991
  • 4
  • 47
  • 70
0

First we make the list of strings that splitlines gives us into a list of lists. Then we can use zip to make tuples of those elements that share indices in those lists.

list(zip(*map(str.split, f.read().splitlines())))

for your input:

[('1', '2', '3', '4', '5', '6'), ('-10', '-10', '0', '10', '10', '0'),
 ('0', '-10', '-10', '-10', '0', '0'), ('0', '0', '0', '0', '0', '0')]
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96