Python: Import a file and convert to a list

后端 未结 8 1994
离开以前
离开以前 2020-12-19 20:02

I need help with importing a file and converting each line into a list.

An example of the file would look like:

p wfgh 1111 11111 111111
287 48 0
656         


        
8条回答
  •  自闭症患者
    2020-12-19 20:39

    p = open('filename')
    
    #List:
    linelist = [line for line in p.readlines()]
    
    """
    But I prefer creating a dictionary as I find them more useful at times. Example here is very trivial. You can use the list index as a line number also.
    """
    
    #Dictionary:
    linedict = dict([(no, line) for no, line in enumerate(p.readlines())])
    

提交回复
热议问题