[Tutor] Diamond Equivalent

bob bgailer at alum.rpi.edu
Fri Sep 23 19:10:13 CEST 2005


At 04:37 AM 9/23/2005, kim.d at tesco.net wrote:
>[snip]
>In perl I can write this:
>
>@array = <>;
>print @array;
>
>If I save that and call it from the command line, I can include the name of a
>file after the script name. It will read in the file, putting each line 
>into an
>element of the array.
>
>I know how to open a specific file using Python. I wanted to know how to give
>a Python script a file name in the command line, and have it open that file.

So there are 2 parts to the question:

(1) how to retrieve command line arguments:

import sys
arg1 = sys.argv[1]

(2) how to read the lines of a file (whose path is in arg1) into an array

array = file(arg1).readlines()

That's all. Of course you don't need an intermediate variable; you can just:

import sys
array = file(sys.argv[1]).readlines()

and if you want to print the results:

print array 



More information about the Tutor mailing list