Basic python file-io variables with enumerate

some1 picture some1 · Jun 24, 2011 · Viewed 23.4k times · Source

New to python and trying to learn the ropes of file i/o.

I am working with pulling lines from a large (2 million line) file in this format:

56fr4
4543d
4343d
5irh3

Here is the function I'm using to return a code:

def getCode(i):
    with open("test.txt") as f:
        for index, line in enumerate(f):
            if index == i:
                code = # what does it equal?
                break
    return code

Once the index gets to the right spot (i), what syntax do I use to set the code variable?

Answer

matchew picture matchew · Jun 24, 2011

code = line.strip()

will assign code to the line number that is equal to i while removing the trailing new line.

you also need to update your code a bit

 def getCode(i):
    with open('temp.txt', 'r') as f:
             for index, line in enumerate(f):
                     if index == i:
                             code = line.strip()
                             return code

why you need .strip()

>>> def getCode(i):
...     with open('temp.txt') as f:
...             for index, line in enumerate(f):
...                     if index == i:
...                             code = line
...                             return code
 ... 
>>> getCode(2)
"                  'LINGUISTIC AFFILIATION',\n"

yes, " 'LINGUISTIC AFFILIATION'," is in my current temp.txt'