Tag: 除外

Python安全的方法来获取嵌套字典的值

例如,我有一个嵌套的字典。 只有一种方法可以使价值安全吗? try: example_dict['key1']['key2'] except KeyError: pass 或者,也许python有像get()嵌套字典的方法?

使用python“with”语句和try-except块

这是正确的方式来使用python“with”语句结合try-except块吗? try: with open("file", "r") as f: line = f.readline() except IOError: <whatever> 如果是这样,那么考虑旧的做事方式: try: f = open("file", "r") line = f.readline() except IOError: <whatever> finally: f.close() 这里的“with”语句的主要好处是我们可以摆脱三行代码? 这个用例对我来说似乎并不令人信服(尽pipe我明白“with”语句有其他用途)。 编辑:上述两个代码块的function是否相同? 编辑2:前几个答案一般谈到使用“与”的好处,但在这里似乎边际利益。 我们已经(或应该已经)明确地调用f.close()多年了。 我想一个好处是,马虎编码器将受益于使用“与”。

pythonexception消息捕获

import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) FTPADDR = "some ftp address" def upload_to_ftp(con, filepath): try: f = open(filepath,'rb') # file to send con.storbinary('STOR '+ filepath, f) # Send the file f.close() # Close file and FTP logger.info('File successfully uploaded […]