Kevin Wong
Kevin Wong

Reputation: 1

Open, read, then store lines into a list in Python

So I've seen this code;

with open(fname) as f:
    content = f.readlines()

in another question. I just need some confirmation on how it works. If I were to have a file named normaltrack.py which contains code;

wall 0 50 250 10
wall 0 -60 250 10
finish 200 -50 50 100

I should have a list called wall = [] and have the opening code as;

with open(normaltrack.py) as f:
    wall = f.readlines()

to open the file and store the lines of code that start with "wall" into the list?

Do I always have the change the "fname" everytime I want to open a different file? Or is there a way to do it from the interpreter? Such as python3 assignment.py < normaltrack.py ?

Upvotes: 0

Views: 305

Answers (3)

Yuan Wang
Yuan Wang

Reputation: 155

this code should work for you

#!/usr/bin/env python
import sys

def read_file(fname):
    call = []
    with file(fname) as f:
        call = f.readlines()
    call = filter(lambda l: l.startswith('wall'), call)
    return call

if __name__ == '__main__':
    fname = sys.argv[1]
    call = read_file(fname)
    print call

Upvotes: 0

molecule
molecule

Reputation: 533

Here's a quick and dirty script that does what you want.

import sys

if len(sys.argv) > 1:
    infile = sys.argv[1]
else:
    print("Usage: {} <infile>".format(sys.argv[0]))
    sys.exit(1)

with open(infile, 'r') as f:
    walls = []
    for line in f:
        if line.startswith('wall'):
            walls.append(line.strip())

If you name this script 'read_walls.py', you can run it from the command line like this,

python read_walls.py normaltrack.py

Ordinarily, I'd use argparse to parse command-line arguments, and write a main() function for the code. (That makes it testable in the interactive python interpreter.)

Upvotes: 0

willnx
willnx

Reputation: 1283

In your example:

with open(fname) as f:
    content = f.readlines()

'fname' is a variable reference to a string. This string is the file path (either relative or absolute).

To read your example file, and generate a list of all lines that with 'wall', you can do this:

fname = '/path/to/normaltrack-example.txt'  # this would be an absolute file path in Linux/Unix/Mac
wall = []
with open(fname) as the_file:
    for line in the_file:
        if line.startswith('wall'):
            wall.append(line) # or wall.append(line.rstrip()) to remove the line return character

In general, it's best to not call 'readlines()' on a file object unless you control the file (that is, it's not something the user provides). This is because readlines will read the entire file into memory, which sucks when the file is multiple GBs.

Upvotes: 1

Related Questions