Reputation: 25
In my txt I have this:
111111111111111111111
101000100000010000001
101011111011111110101
I want to place each line of text file as a row of a matrix, and each 0 and 1 is an array element. For example, M [0] = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ]
And then I could access M[1][1], which contain 0.
Recently I brought a similar question here in the forum and the staff helped me with very lean code and solved very well. The goal was to turn into one list. Follows the code bellow:
with open ( 'arq.txt') the buffer:
l = list (map (int, buffer.read (). replace ('\ n', '')))
print l
Besides my doubt someone could pass me some website with reference to the functions, or a book you already have experiment and recommended for beginner, intermediate. Video lessons. I tried searching on google some website like the http://www.cplusplus.com/reference/ but found nothing similar to the python. The official python does not have examples from each function.
Upvotes: 0
Views: 66
Reputation: 2335
mat = []
with open('data.txt') as fin:
for line in fin:
row = [int(item) for item in line.strip()]
mat.append(row)
Upvotes: 1
Reputation: 43226
You can try this:
with open ( 'arq.txt') as buffer:
mat = list(map(int, line.strip()) for line in buffer)
print mat
Upvotes: 0
Reputation: 2031
Alright, this is quite simple actually. Not the best looking one liner code, but its easy to understand.
Try this:
m = {}
with open("args.txt") as f:
data=f.read().split()
for x in range(len(data)):
m[x]=list(data[x])
print(m)
Upvotes: 1