Python: Import a file and convert to a list

52,004

Solution 1

The following line will create a list where each item is a list. The inner list is one line thats split up into "words".

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

I put the code snippet you posted into a input.txt file in c:\temp and ran this line. Is the output similar to what you want?

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']]

Solution 2

    with open('"input.txt"') as f:
    lines = f.read().splitlines()

this will give you a list of values (strings) you had in your file, with newlines stripped.

Solution 3

fileName=open("d:/foo.bar")
lines = [i for i in fileName.readlines()]

hope that helps :D

Solution 4

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)]
Share:
52,004
harpalss
Author by

harpalss

Updated on February 25, 2020

Comments

  • harpalss
    harpalss about 4 years

    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
    65626 -1818 0
    4654 21512 02020 0
    

    The first line beginning with p is a header and the rest are clauses. Each clause line must begin with a series of at least two integers and finish with a zero

    thanks in advance