-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?

2
  • look here and here. Commented Jan 27, 2017 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] Commented Jan 27, 2017 at 19:34

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Why? What does it do?
I added an explanation.
James, thanks. That was very useful.
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')]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.