Python: import a file and convert it to a list

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

An example file will look like this:

p wfgh 1111 11111 111111
287 48 0
65626 -1818 0
4654 21512 02020 0

The first line starting with p is the heading, and the rest are sentences. Each sentence line must begin with a series of at least two integers and end with zero

early

+3
source share
9 answers

The next line will create a list in which each item is a list. An internal list is a single line divided into “words”.

li = [i.strip().split() for i in open("input.txt").readlines()]

, input.txt c:\temp, . , ?

C:\temp>python
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print([i.strip().split() for i in open("input.txt").readlines()])
[['p', 'wfgh', '1111', '11111', '111111'], ['287', '48', '0'], ['65626', '-1818', '0'], ['4654', '21512', '02020', '0']]
+7
fileName=open("d:/foo.bar")
lines = [i for i in fileName.readlines()]

, : D

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

, , :

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)]
+1

Python

- "readline".

... , .

0

, :

ls=[]
for line in open( "input.txt", "r" ).readlines():
    for value in line.split( ' ' ):
        ls.append( value )

, readlines().

0
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

, , :

  • 1
  • "0"

, , - .

, , . , , :

result_list = read_data('foo.dat')

, , . , linux, python , - , . read_data .

, ( , ap 0, ), , , , .

#!/usr/bin/env python
import sys

def read_data(fn):
    """Reads in datafile

    data file is in format:
        p wfgh 1111 11111 111111
        287 48 0
        65626 -1818 0
        4654 21512 02020 0
    where first line begins with p and is a header, and following lines
    are comprised of at least 2 integers plus a tailing 0.
    Pass in the filename, the resulting list of lists of integers will be 
    returned.
    """
    f = open(fn, 'r')
    # check for header line
    assert(f.readline().split()[0]=='p')
    for l in f:
        d = [int(col) for col in l.split()]
        if not d:
            # skip empty lines
            continue
        # check we have at least 2 integers and the last column is 0
        assert(d[-1] == 0 and len(d) >= 3)
        # yield current line
        yield d[:-1]

if __name__ == '__main__':
    for l in read_data(sys.argv[1]):
        print unicode(l)
0
source
    with open('"input.txt"') as f:
    lines = f.read().splitlines()

this will give you a list of values ​​(lines) that you had in your file, with a line feed.

0
source

Source: https://habr.com/ru/post/1725719/


All Articles