Ok thank you in advance for any help!

The problem:

Write a program that asks the user for the name of a file. The program should display the contents of the file with each line preceded with a line number followed by a colon. The line numbering should start at 1.

The code:

def main():

    #Ask user for file to open
    get_file = input('Please enter filename for file you wish to open: ')

    #open get_file
    open_file = open(get_file, 'r')

    #read line from file
    line = open_file.readline()

    #counter for line
    for count in range[1, line + 1]:
    #make sure file is not over
    while line != '':
    #read next line
        line = open_file.readline()


I get an undefined variable when attempting to open a file.

try using raw_input() instead
and then it is to be believed that there is to be an error expected from within your line 13 o:<

Edited 3 Years Ago by nouth

def main():
    with open(raw_input("Enter file name: ", "r")) as fin:
        for num, line in enumerate(fin.readlines()):
            print("%d: %s"%(num+1, line))

it is without error checking, u
you can add exception catching to it.

You can try this

def enum():
    f =file(raw_input("Please enter filename.txt for file you wish to open: "), "r")
    for n , line in enumerate(f):
         print n+1,":", line

>>> ================================ RESTART ================================
Please enter filename.txt for file you wish to open: data.txt
1 : I love the python programming

2 : How love the python programming

3 : we love the python programming

4 : do you like python for kids?

5 : I like Hello World Computer Programming for Kids and Other Beginners.

Edited 3 Years Ago by tony75

Good,but see how i solve it with enumerate.

Not sure which version of Python you are using, but this should work with Python27 and Python33 ...

''' file_read103.py

assume mynames.txt has these content lines ...

fname = "mynames.txt"
with open(fname) as fin:
    k = 1
    for name in fin:
        # rstrip() removes trailing newline char
        print("{}: {}".format(k, name.rstrip()))
        k += 1

''' result ...
1: Fred
2: Mary
3: Lisa
4: Amy

Thank you very much for all your help! I finally was able to do it with your code with a little modification... Was definitely making it more complicated than it needed to be!

def main():
    fname = input('Please enter filename.txt for file you wish to open: ')
    with open(fname, 'r') as fin:
        k = 1
        for name in fin:
            print("{}: {}".format(k, name.rstrip()))
            k += 1

A more pythonic/better solution is to use enumerate()
enumerate() can take argument,so counting start at 1.

with open('names.txt') as fin:
    for index, name in enumerate(fin, 1):
        print("{}: {}".format(index, name.strip()))

1: Fred
2: Mary
3: Lisa
4: Amy

Edited 3 Years Ago by snippsat

This question has already been answered. Start a new discussion instead.