Python: Import a file and convert to a list

后端 未结 8 1993
离开以前
离开以前 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:53
    fh=open("file")
    mylist=[]
    header=fh.readline().rstrip()
    if not header.startswith("p wncf") :
        print "error"
    header=header.split()
    mylist.append(header)
    if len(header) != 5:
        print "error"
    if False in map(str.isdigit, header[2:]):
        print "Error"
    for line in fh:
        line=line.rstrip().split()
        if False in map(str.isdigit, line[0:2]):
            print "Error"            
        elif line[-1] != 0: 
            print "Error"
        else:
            mylist.append(line)
    fh.close()
    
    0 讨论(0)
  • 2020-12-19 20:57

    To build a list of only the lines in the file that contain at least two integers and end with a zero, use a regular expression:

    import re
    p = re.compile(r'^((\-?\d*\s+){2,})0$')
    with open(filename, 'rb') as f:
        seq = [line.strip() for line in f if p.match(line)]
    
    0 讨论(0)
提交回复
热议问题