[英]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.
我已将此代码编写为一个名为readFile.py的文件,并尝试使用execfile命令通过外壳运行它。 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!!
结果仅显示前两个打印stmts,并且控件未输入def readFile()。我无法找到原因,需要帮助。谢谢!
print 'i am doing fine'
filename = "train-win.dat"
print 'i am doing fine1'
def readFile():
print 'i am doing fine2'
import 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 readFile
but you haven't called it so it will never execute. 您定义了函数
readFile
但尚未调用它,因此它将永远不会执行。 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. p不应该在那里。
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. 尽管您的代码可以使用另一个答案中显示的微小修改来工作,但是编写Python的通常方式以稍微不同的顺序显示代码。 Without the extra
print
statements, I might write: 如果没有多余的
print
语句,我可能会这样写:
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. 第一件事是
import
模块。 Normally this is done at the top of the file. 通常,这是在文件顶部完成的。
The next part defines a function called readFile
. 下一部分定义了一个名为
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. def
语句在执行时实际上并没有执行任何操作,但是Python会记住该块中的语句,以便稍后执行。
Finally, readFile()
actually calls the readFile
function. 最后,
readFile()
实际上会调用readFile
函数。
Note also that I moved f.close()
inside the if
statement. 还要注意,我将
f.close()
移到了if
语句中。 You wouldn't want to try to close f
if it had never been opened in the first place. 如果您从未尝试过将
f
从未打开过,则您不想尝试将其关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.