Skip to content Skip to sidebar Skip to footer

How Can I Make Each Line In A Data File A Tuple In A List Of Tuples?

I have a text file called CustomerList.txt and it looks like this 134998,Madison,Foxwell,825 John Street,Staunton,VA,24401,6655414998 The end result should be like this with open('

Solution 1:

Hopefully, the below will get you started:

Firstly, by default split(), splits by whitespace (i.e. empty space) and you want it to split by a comma - so change it to: .split(',')...

Also, I ran rstrip() to remove the new_line character (\n).

Moreover, you want to zip the headers to each line and not the overall data. Your current 'for loop', loops over the lines (which would each contain a separate data entry), thus the zip needs to be inside it (zipping each individual line) and not outside it (i.e. not zipping the entire data). Also, I personally find it easier to zip an array rather than assigning a long list variables (I'm not sure if that would actually work).

This is how I would start with the first step:

withopen("positionfile.txt", "r") as fin:
    header = ['ID', 'Firstname', 'Lastname', 'Address', 'City', 'State', 'Zip', 'Phone']
    print [zip(header,l.rstrip().split(',')) for l in fin.readlines()]

Post a Comment for "How Can I Make Each Line In A Data File A Tuple In A List Of Tuples?"