python TypeError:必须是没有NULL字节的编码字符串,而不是str

问题描述:

试图熟悉 python 的标准库,并在我的 Windows 机器上对它进行一些处理.使用 python 2.7 我有以下小脚本,它旨在查看目录并在从文件名中删除数字后重命名其中的所有文件.我收到一个类型错误,提示必须是没有 NULL 字节的编码字符串,而不是 str"

Trying to get familiar with python's standard library and doing some mucking around with it on my Windows machine. Using python 2.7 I have the following little script which is intended to look in a directory and rename all of the files therein after removing numerals from the file name. I'm getting a typeerror that says "must be encoded string without NULL bytes, not str"

它调用了第 5 行和第 18 行,在下面注明,其中我使用了 os.path.exists.

it calls out lines 5 and 18, noted below, where im using os.path.exists.

任何帮助将不胜感激!

    import os, re, string, glob

    path = os.path.normpath('C:\Users\me\Photo Projects\Project Name\Project Photos\Modified\0-PyTest')

ln5:if os.path.exists(path):
        print "path exists at " + path
        for file in glob.glob(os.path.join(path, '*.jpg')):
            new_path = os.path.join(os.path.dirname(file), re.sub('\d', '', os.path.basename(file)))
line18:     if not os.path.exists(new_path):
                os.rename(file, new_path)

原来是单反斜杠问题.我认为 os.path.normpath 会按照操作系统的要求格式化路径.

turns out to be the single backslash problem. i thought os.path.normpath would format the path as required by the os.