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!

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.