Python 冒号预期错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35602637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:40:23  来源:igfitidea点击:

Colon expected error

pythonpython-2.7

提问by Leem.fin

I have a simple problem.

我有一个简单的问题。

class MyObj:
   ...
   def get_file_name(self):
    return "myfile.txt" 

some_obj = MyObj()

# Error: Colon expected
with open some_obj.get_file_name() as f:
  print("dealing with file ...")
  # do something on f

MyObjclass has a method called get_file_name(self), which returns a string of file name.

MyObj类有一个名为 的方法get_file_name(self),它返回一串文件名。

In the code of opening the file, I got compiler error Colon expected. I don't see where/why colon needed. Please help me why I got this error?

在打开文件的代码中,我得到了编译器错误Colon expected。我不明白哪里/为什么需要冒号。请帮助我为什么会出现此错误?

采纳答案by rodrigo

This line:

这一行:

with open some_obj.get_file_name() as f:

should be:

应该:

with open(some_obj.get_file_name()) as f:

That is, open()is a function!

也就是说,open()是一个函数!

回答by mvelay

bad syntax in your code, try adding brackets when opening your file:

代码中的语法错误,请在打开文件时尝试添加括号:

# Error: Colon expected
with open(some_obj.get_file_name()) as f:
    print("dealing with file ...")
    # do something on f