使用 Try & 的文件打开功能Python 2.7.1 除外

发布于 2024-12-19 07:14:03 字数 262 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

智商已欠费 2024-12-26 07:14:03

如果您想从 except 块中返回,则需要缩进 return 0。
另外,你的论点没有起到任何作用。我假设您希望这个函数能够测试任何文件,而不是为其分配文件句柄?如果没有,你不需要任何争论。

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

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
冷月断魂刀 2024-12-26 07:14:03

我认为如果您只想“检查”文件是否存在,那么 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.

假面具 2024-12-26 07:14:03

这可能是因为您想以读取模式打开文件。
将“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.

瑕疵 2024-12-26 07:14:03

如果您只想检查文件是否存在,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文