Python - 写入格式化字符串时出现IOError

时间:2014-03-21 14:02:03

标签: python logging ioerror

我在使用logger函数时遇到此异常。我不明白为什么它试图打开我的日志内容。

这是我抛出IOError例外的代码:

try:
    logger(paths['log'], "Renamed %s in %s." % (song.getPath(), song.getTag('title')))
except IOError as err:
    logger(paths['log'], "IOError: %s" % err)

这是我的logger函数:

def logger(log_path, log_content):
    """
    :param log_path: where the log is going to be written
    :param log_content: what to write
    """

    log = open(log_path + "/" + "pynderella.log", 'a')
    log.write("%s: %s\n" % (time.strftime("%d-%m-%y %H:%M:%S"), log_content))
    log.close()

异常输出(不存在的文件是“log_content”参数的一部分[在本例中, song.getPath()!)

IOError: [Errno 2] No such file or directory: 'path/to/a/file/file.ext'

请注意,异常是正确记录的!

修改

的getPath():

    def getPath(self):
    return self.path
Song类的

init ():

    def __init__(self, path):
    """
    :param path: the path of the song
    """
    self.path = os.path.abspath(path)

getTag():

def getTag(self, tag):
    """
    Returns a tag from the song.
    :param tag: which tag wants to be retrieved
    """
    track = None
    if getExtension(self.path) in ['.mp3', '.mpeg3']:
        track = EasyID3(self.path)
    elif getExtension(self.path) == '.mp4':
        track = EasyMP4(self.path)

    try:
        if tag.lower() in ['title', 'artist', 'album']:
            return track[tag][0].encode('ascii', 'ignore')  # it was encoded in unicode
    except Exception as err:
        logger(paths['log'], "Exception getTag: %s" % err)
        return None

编辑2: 这是我的日志文件输出:

21-03-14 16:27:16: Moved /Users/user/pynderella/daemon/source/boh.mp3 in destination/Paramore/All We Know Is Falling.

21-03-14 16:27:16: IOError: [Errno 2] No such file or directory: 'destination/Paramore/All We Know Is Falling/boh.mp3'

1 个答案:

答案 0 :(得分:1)

如果这是您的记录器功能的整个代码,对我而言,您似乎并未关闭该文件。然后文件句柄很忙,您无法打开它以进行另一个日志追加。

即使事实证明这不是导致问题的原因,也可以在记录器功能中尝试使用资源(或try-finally)来确保释放文件上的句柄。