使用 Try & 的文件打开功能Python 2.7.1 除外
def FileCheck(fn):
try:
fn=open("TestFile.txt","U")
except IOError:
print "Error: File does not appear to exist."
return 0
我正在尝试创建一个函数来检查文件是否存在,如果不存在则应该打印错误消息并返回 0 。为什么这不起作用???
def FileCheck(fn):
try:
fn=open("TestFile.txt","U")
except IOError:
print "Error: File does not appear to exist."
return 0
I'm trying to make a function that checks to see if a file exists and if doesn't then it should print the error message and return 0 . Why isn't this working???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想从 except 块中返回,则需要缩进 return 0。
另外,你的论点没有起到任何作用。我假设您希望这个函数能够测试任何文件,而不是为其分配文件句柄?如果没有,你不需要任何争论。
You'll need to indent the return 0 if you want to return from within the except block.
Also, your argument isn't doing much of anything. Instead of assigning it the filehandle, I assume you want this function to be able to test any file? If not, you don't need any arguments.
我认为如果您只想“检查”文件是否存在,那么 os.path.isfile() 会更好,因为您不需要实际打开该文件。无论如何,打开文件后关闭文件被认为是最佳实践,上面的示例不包括这一点。
I think
os.path.isfile()
is better if you just want to "check" if a file exists since you do not need to actually open the file. Anyway, after open it is a considered best practice to close the file and examples above did not include this.这可能是因为您想以读取模式打开文件。
将“U”替换为“r”。
当然,您也可以使用 os.path.isfile('filepath') 。
This is likely because you want to open the file in read mode.
Replace the "U" with "r".
Of course, you can use
os.path.isfile('filepath')
too.如果您只想检查文件是否存在,Python os 库提供了解决方案,例如 os.path.isfile('TestFile.txt')。 OregonTrails 答案不起作用,因为您仍然需要最后使用 finally 块关闭文件,但要做到这一点,您必须将文件指针存储在 try 和 except 块之外的变量中,这违背了解决方案的整个目的。
If you just want to check if a file exists or not, the python os library has solutions for that such as
os.path.isfile('TestFile.txt')
. OregonTrails answer wouldn't work as you would still need to close the file in the end with a finally block but to do that you must store the file pointer in a variable outside the try and except block which defeats the whole purpose of your solution.