How can I make each line in a data file a tuple in

2019-09-16 15:07发布

问题:

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("CustomerList.txt", "r") as fin:
    ID, Firstname, Lastname, Address, City, State, Zip, Phone = zip(*[l.split() for l in fin.readlines()])

That's what I have so far, but I get an error that says I need more than 3 values to upack. I just started using tuples yesterday so please keep things as basic as possible for this newbie. If you could include an explanation as to why it worked that would be great!

Step 1: Each line in the data file should become a tuple in a list of tuples (or a list within a list). It would need to be before what I created in the last program which is this.

Step 2: Inside of the returning function I'll need to get a ID number (like 134998) to search for a match and if a match is found return it as a tuple/list if not return an empty tuple/list. They can be strings because they aren't calculations.

回答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:

with open("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()]