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
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()
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)]