Try this:
def getTuple():
with open('file.txt', 'r') as file:
result = []
matrix = []
result.extend(map(int, file.readline().split()))
for line in file:
matrix.append(line.split())
result.append(matrix)
return tuple(result)
print(getTuple())
Outputs:
(3, 5, [['o', 'x', 'o', 'x', 'o'], ['o', 'o', 'o', 'x', 'x'], ['o', 'o', 'o', 'o', 'o']])
However, your code was returning:
(['3 5\n'], ['o x o x o\n'], ['o o o x x\n'], ['o o o o o'])
Let me walk you though the logic behind possible implementation (The points also point out the issues in your code):
You need to read/treat the first line differently than the rest of the lines in your file (it contains the number of rows and columns). You need to split the first line using split() method (without any argument passed to it, see this to know what difference it makes) and then use map() to convert each element in the first line to int. The object returned by map() (map object in Python 3.x) (See this to learn more about map) is used to extend the list result
.
Other lines needs to be split using split()
and then appended to a list matrix
. After the end of the for loop, we can append the matrix to the list result
.
- See this to learn more about syntax used by me to manage the file resource (
with open('file.txt', 'r') as file
).