Home > Software design >  Convert data from text file to tuples
Convert data from text file to tuples

Time:12-03

I have a text file in this form:

ID1

NUMBER1

NUMBER2 

ID2

NUMBER3

NUMBER4

The desired outpt is: (ID1,NUMBER1),(ID1,NUMBER2),(ID2,NUMBER3)(ID2,NUMBER4).

I think it must be converted to tuples. But I am still stuck on how to get the desired output.

This is my code so far:

with open("outfile.txt") as f:
    for line in f:
          print(line, type(line))

I will get the file line by line with type "str"

CodePudding user response:

Try this:

tuples = []
with open("outfile.txt") as f:
    current_id = ''
    for line in f:
        if line.startswith('ID'):
            current_id = line
        elif line.startswith('NUMBER'):
            tuples.append((current_id, line))
print(tuples)
  • Related