0

Code example that I'm stuck on:

import sys
with open(sys.argv[1],'r') as infile:
    num = 0
    for line in infile:
        num += 1
        print num, line,

I've just started Python and gone through the most basic of basics, however reading some class notes I couldn't quite understand this part (pasted above). How does with work and what is it doing here? as seems to be linked with the with in doing something but I can't quite make it out and what I've seen online doesn't make sense when compared to this. An explanation on how its used in this particular situation would really help.

Also this code is at the start of the input / output section of my notes, how is code using input and output?

darkphoton
  • 85
  • 7
  • sorry about the confusion but I also have trouble understanding what the code means as a whole and the sys.argv[1] which is why looking up "with" statements online and on this site didnt solve this piece of code for me. – darkphoton Nov 22 '14 at 21:11

2 Answers2

1

with is used with context managers. In this case the resource being managed is the open infile which must be closed. The file will be closed when the with block is exited even if an exception is thrown inside the block. as is used with with to give a name to the context manager. The as clause is optional.

For more information you can read the following resources:

sys.argv is a list containing the command line arguments passed to the script when running it. In this case the assumption is that sys.argv[1] names a path to a file for reading. Traditionally, sys.argv[0] is the script name, so sys.argv[1] is actually the first argument.

b4hand
  • 9,550
  • 4
  • 44
  • 49
1

Yes, the with and as keywords are both parts of Python's with-statement.

sys.argv[1] is presumably a path to a file. Opening a file with a with-statement ensures that it is automatically closed when control leaves the with-statement's code block. Moreover, the file object returned by open will be accessible through the name infile.

In other words, this code:

with open(sys.argv[1],'r') as infile:
    ...

tells Python to:

  1. Open the file at the path given by sys.argv[1].

  2. Assign the name infile to this file object.

  3. Close the file automatically when we leave the following code block (represented by ...).

The equivalent code would be:

import sys

infile = open(sys.argv[1],'r')

num = 0
for line in infile:
    num += 1
    print num, line,

infile.close()