GVKun编程网logo

了解Python的“ with”语句(python的with用法)

21

本文将介绍了解Python的“with”语句的详细情况,特别是关于python的with用法的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于java

本文将介绍了解Python的“ with”语句的详细情况,特别是关于python的with用法的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于javascript – 将“if / then..else”语句与“switch”语句组合在一起、python – 用于打开具有两个函数的文件的“with”语法、Python“ with”语句的作用是什么?、python“ with”语句的用途是什么?的知识。

本文目录一览:

了解Python的“ with”语句(python的with用法)

了解Python的“ with”语句(python的with用法)

我试图了解这些之间是否存在差异,以及该差异可能是什么。

选项一:

file_obj = open(''test.txt'', ''r'')with file_obj as in_file:    print in_file.readlines()

选项二:

with open(''test.txt'', ''r'') as in_file:    print in_file.readlines()

我知道,对于选项一,file_objwith块之后处于闭合状态。

答案1

小编典典

我不知道为什么没有人提到这一点,因为这是工作方式with的基础。与Python中的许多语言功能一样,with在后台调用特殊方法,这些方法已经为内置Python对象定义,并且可以由用户定义的类覆盖。在with特定情况下(和上下文管理器),方法是__enter____exit__

请记住,在Python中, 所有东西都是对象
-甚至是文字。这就是为什么您可以做类似的事情''hello''[0]。因此,是否直接使用由以下文件返回的文件对象并不重要open

with open(''filename.txt'') as infile:    for line in infile:        print(line)

或先使用其他名称存储(例如,将长行分开):

the_file = open(''filename'' + some_var + ''.txt'')with the_file as infile:    for line in infile:        print(line)

因为最终的结果是the_fileinfile和返回值open都指向同一个对象,这就是with被调用__enter____exit__方法上。内置文件对象的__exit__方法是关闭文件的方法。

javascript – 将“if / then..else”语句与“switch”语句组合在一起

javascript – 将“if / then..else”语句与“switch”语句组合在一起

我必须并排显示两个数字(都以zero.gif文件开头).每个数字都需要一个输入区域供用户输入1到5之间的数字和一个显示“Process Number”的按钮,然后弹出相应的数字.

我必须为一个使用if-then-else语句,为另一个使用switch语句.我分别理解这两个,但我不知道如何在脚本代码中将两者结合起来.

目前,当我在第一个输入框中输入数字时,它们都会同时更改.如果我尝试第二个框,我会收到警告“你必须选择1到5之间的数字”.

所以我不确定如何将两者分开.我使用了不同的图像ID,但它不起作用.这是所有代码.

<script type="text/javascript">
    function processNumber() {
      var numberInput = document.getElementById("userInput").value;

      // test for valid input number from 1 to 5
      if (numberInput < 1 || numberInput > 5) {
        alert("Your number must be from 1 to 5");
        return;

      }


      if (numberInput == 1)
        document.getElementById("ones").src="images/one.gif";
      else if (numberInput == 2)
        document.getElementById("ones").src = "images/two.gif";
      else if (numberInput == 3)
        document.getElementById("ones").src = "images/three.gif";
      else if (numberInput == 4)
        document.getElementById("ones").src = "images/four.gif";
      else if (numberInput == 5)
        document.getElementById("ones").src = "images/five.gif";
      else alert("Sorry - your input is not recognized");
      // likely a non numeric was entered if we got here


      switch (numberInput) {
        case "1": document.getElementById("group").src = "images/one.gif";
          break;
        case "2": document.getElementById("group").src = "images/two.gif";
          break;
        case "3": document.getElementById("group").src = "images/three.gif";
          break;
        case "4": document.getElementById("group").src = "images/four.gif";
          break;
        case "5": document.getElementById("group").src = "images/five.gif";
          break;

        default: alert("Sorry - your input is not recognized");

          // default in case a non numeric was entered
      } // end switch (numberInput)
    } // end function processNumber()

</script>

解决方法

一个简单的解决方案可以是一个字符串数组:
var numbers = ["zero","one","two","three","four","five"];

if (numbers[numberInput] != undefined) {
   document.getElementById("ones").src = "images/" + numbers[numberInput] + ".gif";
   document.getElementById("group").src = "images/" + numbers[numberInput] + ".gif";
}
else 
   alert("Sorry - your input is not recognized");

我想保持清洁,但这只是其中一个解决方案.如果你经常使用它,你可以发挥作用.

python – 用于打开具有两个函数的文件的“with”语法

python – 用于打开具有两个函数的文件的“with”语法

假设我想使用以下语法打开一个文本文件进行阅读:
with open(fname,'r') as f:
    # do something
    pass

但如果我发现它以.gz结尾,我会调用gzip.open().

if fname.endswith('.gz'):
    with gzip.open(fname,'rt') as f:
            # do something
            pass
else:
    with open(fname,'r') as f:
            # do something
            pass

如果“做某事”部分很长并且不方便在函数中写入(例如,它会创建一个无法序列化的嵌套函数),使用gzip.open或基于返回的打开调用的最短方法是什么? fname.endswith( ‘广州’)?

解决方法

上下文管理器帮助关闭对象.

但是,您不必创建用作上下文管理器的对象,同时使用它来输入上下文. open()和gzip.open()调用返回一个恰好是上下文管理器的新对象,您可以在输入上下文之前创建它们:

if fname.endswith('.gz'):
    f = gzip.open(fname,'rt')
else:
    f = open(fname,'r')

with f:
    # do something

在这两种情况下,对象在进入上下文时返回self,因此这里不需要使用f作为f.

此外,函数是一等公民,因此您还可以使用变量来存储函数,然后在with语句中调用它来创建上下文管理器和文件对象:

if fname.endswith('.gz'):
    opener = gzip.open
else:
    opener = open

with opener(fname,'rt') as f:  # yes,both open and gzip.open support mode='rt'
    # do something

这并没有真正为你带来任何其他方法,但你可以使用字典将扩展名映射到callables,如果你愿意的话.

底线是calls context-manager hook methods,没有更少,仅此而已.应用之后的表达式应该提供这样的管理器,但是创建该对象不受上下文管理协议的约束.

Python“ with”语句的作用是什么?

Python“ with”语句的作用是什么?

我试图理解python中的with语句。我到处都在谈论打开和关闭文件,并打算替换try-
finally块。有人也可以发布其他示例吗?我只是尝试烧瓶,里面有大量的语句。绝对要求某人对此进行澄清。

答案1

小编典典

有一个非常好的解释这里。基本上,with语句在关联的对象上调用两个特殊的方法。__enter__和__exit__方法。enter方法返回与“with”语句关联的变量。在语句执行后执行任何清理(例如关闭文件指针)后调用__exit__方法。

python“ with”语句的用途是什么?

python“ with”语句的用途是什么?

如何解决python“ with”语句的用途是什么??

我相信这已经在我之前的其他用户那里得到了回答,因此我仅出于完整性的考虑而添加:该with语句通过将通用的准备工作和清理任务封装在所谓的上下文管理器中来简化异常处理。可以在PEP 343中找到更多详细信息。例如,该open语句本身就是一个上下文管理器,它使你可以打开文件,只要with在使用它的语句上下文中执行该文件,就可以保持打开状态,并在离开上下文后立即将其关闭,无论你是因为异常还是在常规控制流程中离开了它。with因此,可以使用类似于C ++中的RAII模式的方式使用该语句:with语句并在你离开with上下文时释放。

一些示例是:使用打开文件,使用with open(filename) as fp:获取锁with lock:(在lock的实例threading.Lock)。你还可以使用中的contextmanager装饰器来构造自己的上下文管理器contextlib。例如,当我不得不临时更改当前目录然后返回到原来的位置时,我经常使用它:

from contextlib import contextmanager
import os

@contextmanager
def working_directory(path):
    current_dir = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(current_dir)

with working_directory("data/stuff"):
    # do something within data/stuff
# here I am back again in the original working directory

这是另一个示例,该示例临时重定向sys.stdin,sys.stdout并重定向sys.stderr到其他文件句柄并稍后将其还原:

from contextlib import contextmanager
import sys

@contextmanager
def redirected(**kwds):
    stream_names = ["stdin", "stdout", "stderr"]
    old_streams = {}
    try:
        for sname in stream_names:
            stream = kwds.get(sname, None)
            if stream is not None and stream != getattr(sys, sname):
                old_streams[sname] = getattr(sys, sname)
                setattr(sys, sname, stream)
        yield
    finally:
        for sname, stream in old_streams.iteritems():
            setattr(sys, sname, stream)

with redirected(stdout=open("/tmp/log.txt", "w")):
     # these print statements will go to /tmp/log.txt
     print "Test entry 1"
     print "Test entry 2"
# back to the normal stdout
print "Back to normal stdout again"

最后,另一个示例创建一个临时文件夹并在离开上下文时清理它:

from tempfile import mkdtemp
from shutil import rmtree

@contextmanager
def temporary_dir(*args, **kwds):
    name = mkdtemp(*args, **kwds)
    try:
        yield name
    finally:
        shutil.rmtree(name)

with temporary_dir() as dirname:
    # do whatever you want

解决方法

with今天是第一次遇到Python 语句。我已经使用Python几个月了,甚至不知道它的存在!考虑到它的地位有些晦涩,我认为值得一问:

  1. Python with语句旨在用于什么?
  2. 你用它来做什么?
  3. 我需要了解任何陷阱,还是与其使用相关的常见反模式?有什么try..finally比这更好用的情况with吗?
  4. 为什么没有更广泛地使用它?
  5. 哪些标准库类与之兼容?

关于了解Python的“ with”语句python的with用法的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于javascript – 将“if / then..else”语句与“switch”语句组合在一起、python – 用于打开具有两个函数的文件的“with”语法、Python“ with”语句的作用是什么?、python“ with”语句的用途是什么?等相关内容,可以在本站寻找。

本文标签: