windows python TypeError:必须是没有NULL字节的编码字符串,而不是str
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12591575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python TypeError: must be encoded string without NULL bytes, not str
提问by rakitin
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"
试图熟悉 python 的标准库并在我的 Windows 机器上对它进行一些处理。使用 python 2.7 我有以下小脚本,它旨在查看目录并在从文件名中删除数字后重命名其中的所有文件。我收到一个类型错误,提示“必须是没有 NULL 字节的编码字符串,而不是 str”
it calls out lines 5 and 18, noted below, where im using os.path.exists.
它调用了第 5 行和第 18 行,如下所示,其中我使用了 os.path.exists。
Any help would be greatly appreciated!
任何帮助将不胜感激!
import os, re, string, glob
path = os.path.normpath('C:\Users\me\Photo Projects\Project Name\Project Photos\Modifiedr'C:\Users\me\Photo Projects\Project Name\Project Photos\Modified##代码##-PyTest'
-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)
采纳答案by rakitin
turns out to be the single backslash problem. i thought os.path.normpath would format the path as required by the os.
原来是单反斜杠问题。我认为 os.path.normpath 会按照操作系统的要求格式化路径。
回答by Demian
"...Photos\Modified\0-PyTest"
“...照片\修改\0-PyTest”
Its taking the \0 as a null character. You have to escape \
using \\
, or just put an r
before the string to make it raw:
它将 \0 作为空字符。您必须\
使用进行转义\\
,或者只是r
在字符串前放置一个以使其原始:
回答by 0x Tps
If you are giving a path url just add r before it :
如果您提供路径 url,只需在它之前添加 r :
(r'E:\Images\1.png')
(r'E:\Images\1.png')