0

I have a .txt file with some data in it that I would like to transfer into a tuple. I'm able to do that but am having trouble with the format I would like it in. If my .txt file looks something like:

North America, 1, 5
South America, 2, 4
Europe, 3, 3

And I would like to import that into a tuple so it reads:

>>> continent= [("North America", 1, 5), ("South America", 2, 4), ("Europe", 3, 3)]

But those closest I can get close is by:

data = ()
lst = []
infile = open('data.txt', 'r')
for line in infile:
    data = line.strip()
    lst.append(data)
infile.close()
continent = [ tuple(item.split("\t")) for item in file ]
print continent

But this returns the tuple items as:

>>>[('North America, 1, 5'), ('South America, 2, 4'), ('Europe, 3, 3')]

Is there a way to reformat the data so it doesn't give back the whole line in apostrophes (' ') but just gives back the continents names in quotes (" ") and leaves the numbers alone? Thanks!

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by group256
0
fp = open('text.txt', 'r')

t = ()
data = []
line = fp.readline()

while len(line) != 0:
   e1, e2, e3 = line.split(',')
   t = e1, e2, e3.rstrip()
   data.append(t)
   line = fp.readline()
   
fp.close()
   
print data

Remember, you can't add or delete from tuple!!!!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.