【问题标题】:conditional skip in python ifpython中的条件跳过if
【发布时间】:2010-01-08 05:23:24
【问题描述】:

我正在尝试这样的事情

def scanthefile():
    x = 11
    if x > 5
        """ i want to come out of if and go to end of scanfile """
        print x

     return info

更新:

如果必须检查文件的内容大小。如果内容大小大于一个值,比如 500 ,那么我应该转到扫描文件的末尾

【问题讨论】:

  • x = 11; if x > 5?这总是正确的。这有什么意义?即使有更新,这个问题也没什么意义。你能重写这个问题,让它有意义吗?你能——例如——删除没有意义的代码吗?
  • 这个问题是一个关于如何不问的很好示例。你应该首先问“我如何在 python 中检查文件的内容大小”——而不是粘贴一些任意的、部分的尝试而不告诉你要做什么。

标签: python if-statement


【解决方案1】:

如果我理解你的问题,但我真的不确定我是否理解,你可以取消缩进:

x = 11
if x > 5:
    pass # Your code goes here.
print x

【讨论】:

    【解决方案2】:

    “转到文件末尾”是指“查找到文件末尾”吗?那么:

    import os
    
       ...
    
    if x > 5:
      thefile.seek(0, os.SEEK_END)
    

    如果你的意思完全不同,你最好澄清一下!

    【讨论】:

      【解决方案3】:

      好的,所以回答你的更新:

      import os
      
      fn = 'somefile.txt'
      thefile = open(fn, 'r')
      
      # The next line check the size of the file. Replace "stat(fn).st_size" with your own code if you want.
      if stat(fn).st_size > 500:
          thefile.seek(0, os.SEEK_END)
      # you are now at the end of the file if the size is > 500
      

      【讨论】:

        【解决方案4】:

        我理解这个问题的方式是你想打破一个 if 语句,你不能这样做。

        但是,您可以将其替换为 while 循环

        def scanthefile():
            x = 11
        
            while x > 5:
                # do something here...
                if CONTENTSIZE > 500:
                    break
                # do something else..
                break # Which will make the while loop only run once.
        
            return info
        

        【讨论】:

          猜你喜欢
          • 2020-09-29
          • 1970-01-01
          • 1970-01-01
          • 2015-07-12
          • 1970-01-01
          • 2017-05-15
          • 1970-01-01
          • 2015-12-24
          • 2019-03-26
          相关资源
          最近更新 更多