开发者

Please let me know the problem in the following python code

I am trying to written this code which would just test whether a file exists and then reads it and prints. I have written this code as a file named readFile.py and trying to run it through shell using execfile command. I have put many print stmts to check till where the control is going. The result shows me only first two print stmts and the control is not entering the def readFile()..I am unable to find the reason and need help.Thanks!!

print 'i am doing fine'
filename = "train-win.dat"
print 'i am doing fine1'
def readFile():
        print 'i am doing fine2'
        impor开发者_JS百科t os
        print 'i am doing fine3'

        if os.path.exists(filename):
                print 'i am doing fine4'
                f = open(filename,"r")
                print 'i am doing fine5'
                a = f.readlines()
                print 'i am doing fine6'
                print a
                print 'i am doing fine7'
        f.close()p


You define the function readFilebut you haven't called it so it will never execute. Add this at the end of your file (not indented):

readFile()

Also you have a syntax error on the last line of the function:

 f.close()p

That p shouldn't be there.

After making both these changes your program seems to work.


While your code will work with minor modifications shown in another answer, the usual way of writing Python presents code in a slightly different order. Without the extra print statements, I might write:

import os

def readFile():
    if os.path.exists(filename):
        f = open(filename, "r")
        a = f.readlines()
        print a
        f.close()

filename = "train-win.dat"
readFile()

The first thing is to import the modules. Normally this is done at the top of the file.

The next part defines a function called readFile. The def statement doesn't actually do anything at the time it's executed, but Python remembers the statements within the block to be executed later.

Finally, readFile() actually calls the readFile function.

Note also that I moved f.close() inside the if statement. You wouldn't want to try to close f if it had never been opened in the first place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜