Akshay
Akshay

Reputation: 2763

How to read a text file and group them in tuple?

I am new to python and trying to do the following in python 3

I have a text file like this

1 2 3
4 5 6
7 8 9
.
.

I wanted this to be converted into groups of tuple like this

((1,2,3),(4,5,6),(7,8,9),...)

I have tried using

f = open('text.txt', 'r')
f.readlines()

but this is giving me a list of individual words.

could any one help me with this?

Upvotes: 0

Views: 1034

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 90919

A method using csv module -

>>> import csv
>>> f = open('a.txt','r')
>>> c = csv.reader(f,delimiter='\t') #Use the delimiter from the file , if a single space, use a single space, etc.
>>> l = []
>>> for row in c:
...     l.append(tuple(map(int, row)))
...
>>> l = tuple(l)
>>> l
(('1', '2', '3'), ('4', '5', '6'), ('7', '8', '9'))

Though if you do not really need the tuples , do not use them, it may be better to just leave them at list.

Both row and l in above code are initially lists.

Upvotes: 4

Avinash Raj
Avinash Raj

Reputation: 174706

You may try this,

>>> s = '''1 2 3
4 5 6
7 8 9'''.splitlines()
>>> tuple(tuple(int(j) for j in i.split()) for i in s)
((1, 2, 3), (4, 5, 6), (7, 8, 9))

For your case,

tuple(tuple(int(j) for j in i.split()) for i in f.readlines())

Upvotes: 2

Related Questions