views:

138

answers:

7

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  A: 
  1. Open the file
  2. Read each line and parse the line via line.split( )
Amit
+1, it's fine provided that command does not contain spaces
Antony Hatchkins
Does any command contain spaces?
Amit
+9  A: 

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']]
Robert Christie
The OP wants to read it from a file.
Amit
@Amit: Added file processing steps
Robert Christie
Thanks, very much everybody, you all have been a great help
mikip
+3  A: 

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])
    ...
Yin Zhu
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 DeSimone
@Mike, yeah, but usually a parameter file is not big... and a `print lines' could direct see if the file loads correctly or not..
Yin Zhu
+5  A: 
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())
James Hopkin
+1, I was planning to post very similar way.
S.Mark
+1  A: 
>>> 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']]
ghostdog74
+1 Well-spotted that the OP wanted an integer for the index
James Hopkin
I like the solution but it doesnt work if there are are zero parameters in the command
mikip
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...
ghostdog74
Thanks ghostdog
mikip
A: 

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

abhiomkar
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.
SilentGhost
@SilentGhose edited my code now, Thanks for suggesting. Yah, It was very unpythonic. Is it ok now?
abhiomkar
it's better, but you don't need to "declare" `lin`.
SilentGhost
we shall assume that `list_of_commands.txt` is actually a string ;)
SilentGhost
I thought so. I removed 'lin' already! Thx! :)
abhiomkar
I've corrected a few bits, removing redundant 4th line and `.readlines` method, as well as producing actual output
SilentGhost
Thx SilentGhose! :)
abhiomkar
+1  A: 

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):
    ...
van
you don't need brackets there in the unpacking version
SilentGhost
fair enough; just a habit :)
van