简体   繁体   中英

Conditional list Python

I am opening all the files present in zip, then converting the string to List and thereafter, breaking the list into 5 elements from each line.

My code:

with zipfile.ZipFile(dummy.zip, 'r') as mz:
    for f in mz.namelist():
        data = mz.read(f).decode('utf-8').replace("\n", '').replace("\r", ',').lstrip().rstrip().split(",") #Removing all spaces and \r from text.
        allist = [data[i:i + 5] for i in range(len(data))[::5]] #breaking list into 5 elements each

I am able to do it perfectly if all values are present but if any of the element in missing on particular line then it picks up the value from second line but I want to add NA at place of missing element.

File data: Dummy.zip = "File1 + File2"

File1:

Yuli, yu@test.com, 0001, 8902
Su, su@test.com, 0002, 8903, Manager

File:2

Zaon, zn@test.com, 100, 9087, Analyst
June, ju@test.com, 278, 6078

Purpose of the code:

I am adding converting this list to dict, so adding keys to each entry as name, email, ext, Empid, Level

You can do it like this:

texts = [b"Yuli, yu@test.com, 0001, 8902\r\nSu, su@test.com, 0002, 8903, Manager",
         b"Zaon, zn@test.com, 100, 9087, Analyst\r\nJune, ju@test.com, 278, 6078"]

result =[]
keys = "name,email,ext,Empid,Level".split(",")
# you do: 
# with zipfile.ZipFile(dummy.zip, 'r') as mz: 
#     for f in mz.namelist(): 
#         t = mz.read(f) here instead
# instead
for t in texts:
    for line in t.decode("utf-8").split("\n"):
        d = {k:"NA" for k in keys} # init all keys with NA
        # update with actual values
        d.update(zip(keys,(l.strip() for l in line.strip().split(","))))
        # add to result list
        result.append(d) 
print(result)

Output:

[{'name': 'Yuli', 'email': 'yu@test.com', 'ext': '0001', 'Empid': '8902', 'Level': 'NA'}, 
 {'name': 'Su', 'email': 'su@test.com', 'ext': '0002', 'Empid': '8903', 'Level': 'Manager'},
 {'name': 'Zaon', 'email': 'zn@test.com', 'ext': '100', 'Empid': '9087', 'Level': 'Analyst'}, 
 {'name': 'June', 'email': 'ju@test.com', 'ext': '278', 'Empid': '6078', 'Level': 'NA'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM