Home > Software engineering >  Python: Reading from a list of files where we read and return a list of tuples from the data in the
Python: Reading from a list of files where we read and return a list of tuples from the data in the

Time:10-12

I'm creating a function that takes in a list of files (all strings) with each having the format:

File 1:

x,y

x1,y1

File2:

x2,y2

x3,y3

I need to return both files in a single list of tuples. I currently have the function reading thru the file and split/stripping it as so:

newLst
lst = [(tuple(x.strip().split()) for x in y]
newLst.append(lst)

A couple issues I'm having:

  • I'm getting a list per file (in this case 2 lists within a list) when I need them to be one big list of all the tuples [[('x,y',), ('x1, y1',)],[('x2, y2',), ...)]]
  • My tuples instead of ('x','y') it's returning as ('x,y',) with an extra comma

Expected Output:

[('x','y'), ...('x2','y2')]

CodePudding user response:

  1. Use extend() to extend a list by appending elements from another iterator.

  2. You should split the string by ',', and then make results as a tuple.

def extend_from_file(file, lst):
    with open(file, 'r') as f:
        lst.extend([tuple(x.strip().split(',')) for x in f if x.strip()]) # and skip blank lines
  • Related