1

I have a program which reads commands from a text file

for example, the command syntax will be as follows and is a string

'index command param1 param2 param3'

The number of parameters is variable from 0 up to 3 index is an integer command is a string all the params are integers

I would like to split them so that I have a list as follows

[index,'command',params[]]

What is the best way to do this?

Thanks

1
  • Will the string contain spaces? Commented Jan 13, 2010 at 9:58

7 Answers 7

8

Not sure if it's the best way, but here's one way:

lines = open('file.txt')
for line in lines:
   as_list = line.split()
   result = [as_list[0], as_list[1], as_list[2:]]
   print result

Result will contain

['index', 'command', ['param1', 'param2', 'param3']]
Sign up to request clarification or add additional context in comments.

2 Comments

@Amit: Added file processing steps
Thanks, very much everybody, you all have been a great help
5
def add_command(index, command, *params):
    index = int(index)
    #do what you need to with index, command and params here

with open('commands.txt') as f:
    for line in f:
        add_command(*line.split())

Comments

2

i typically write:

lines = open('a.txt').readlines()
for line in lines:
    para = lines.split()
    index = int(para[0])
    command = para[1]
    para1 = float(para[2])
    ...

2 Comments

I'd recommend the first two lines be f = open(filename) and for line in f:, which avoids reading the whole file into memory.
@Mike, yeah, but usually a parameter file is not big... and a `print lines' could direct see if the file loads correctly or not..
1
  1. Open the file
  2. Read each line and parse the line via line.split( )

Comments

1
>>> for line in open("file"):
...     line=line.rstrip().split(" ",2)
...     line[0]=int(line[0])
...     line[2]=line[2].split()
...     print line
...
[1, 'command', ['param1', 'param2', 'param3']]

2 Comments

I like the solution but it doesnt work if there are are zero parameters in the command
its rather easy to insert code for checking. you can check whether length of list is always 3 and then do the necessary. Or use try/except etc etc...many ways...
1

If you use Python 3+, then following should be enough as indicated in PEP 3132: Extended Iterable Unpacking:

(index,command,*parameters) = line.split()

Otherwise, I like solution from James best:

def add_command(index, command, *params):
    ...

1 Comment

you don't need brackets there in the unpacking version
0

The Answer provided by cb160 is correct and smart way, But, I did it in this way. In cb160's code, Only thing is index should be in Integer format, as you have mentioned.

In my below code, I added exceptions for empty lines in input file if there are any.

#Example Input File: (file content)
"""
1 command1 parm1a parm1b parm1c
2 command2 parm2a parm2b parm2c

3 command3 parm3a parm3b parm3c

"""

li = []

for line in open('list_of_commands.txt'):
  try:
    lis = line.split()
    li.append([int(lis[0]),lis[1], lis[2:]])
  except IndexError:
    pass    # do nothing if empty lines are found

print li

Output

[1, 'command1', ['parm1a', 'parm1b', 'parm1c']]
[2, 'command2', ['parm2a', 'parm2b', 'parm2c']]
[3, 'command3', ['parm3a', 'parm3b', 'parm3c']]

let me know if I missed anything.

Thanks

5 Comments

why are you splitting a single line three times? along with empty lines you're catching partial lines. I'd say this code is rather inferior to already posted versions.
@SilentGhose edited my code now, Thanks for suggesting. Yah, It was very unpythonic. Is it ok now?
it's better, but you don't need to "declare" lin.
we shall assume that list_of_commands.txt is actually a string ;)
I've corrected a few bits, removing redundant 4th line and .readlines method, as well as producing actual output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.