Read file as a list of tuples

前端 未结 3 1495
慢半拍i
慢半拍i 2021-02-09 09:03

I want to read a text file using Python. My list must be like this:

mylist = [(-34.968398, -6.487265), (-34.969448, -6.488250),
          (-34.967364, -6.492370)         


        
3条回答
  •  灰色年华
    2021-02-09 10:10

    Yes Cyber solution is best.

    For beginners

    1. Read file in Read mode.
    2. Iterate lines by readlines() or readline()
    3. Use split(",") method to split line by '
    4. Use float to convert string value to float. OR We can use eval() also.
    5. Use list append() method to append tuple to list.
    6. Use try except to prevent code from break.

    Code:

    p = "/home/vivek/Desktop/test.txt"
    result = []
    with open(p, "rb") as fp:
        for i in fp.readlines():
            tmp = i.split(",")
            try:
                result.append((float(tmp[0]), float(tmp[1])))
                #result.append((eval(tmp[0]), eval(tmp[1])))
            except:pass
    
    print result
    

    Output:

    $ python test.py 
    [(-34.968398, -6.487265), (-34.969448, -6.48825), (-34.967364, -6.49237), (-34.965735, -6.582322)]
    

    Note: A readline() reads a single line from the file.

提交回复
热议问题