文件打开功能,Try& Python 2.7.1除外 [英] File Open Function with Try & Except Python 2.7.1
本文介绍了文件打开功能,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。为什么不能正常工作???
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???
推荐答案
如果您想从内部返回,您需要缩进返回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.
def FileCheck(fn):
try:
open(fn, "r")
return 1
except IOError:
print "Error: File does not appear to exist."
return 0
result = FileCheck("testfile")
print result
这篇关于文件打开功能,Try& Python 2.7.1除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文