[英]What does this error mean when I use `os.walk` to get the files path on python 3?
the error is too long so I haven't put it in the title. 错误太长,因此我没有将其放在标题中。 Here is the error: 这是错误:
Traceback (most recent call last):
File "./auto_change_shebang_and_permission.py", line 12, in <module>
shebang = f.readline()
File "/usr/lib/python3.4/codecs.py", line 319, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8c in position 3: invalid start byte
However I've never seen this error before. 但是我以前从未见过此错误。 I written a program to auto change the SheBang on Linux and it use os.walk
to get the files path and open them, here is the program: 我写了一个程序来自动更改Linux上的SheBang ,它使用os.walk
获取文件路径并打开它们,这是程序:
for root, dirs, files in os.walk(sys.argv[1]):
for name in files:
# to except the hidden file
if root[:3] == './.':
pass
elif name[0] == '.':
pass
# open the file, read the SheBang, and change it.
else:
with open(os.path.join(root, name), 'r') as f:
shebang = f.readline()
if shebang[:2] != '#!':
with open(os.path.join(root, name), 'w') as e:
e.write('#!/usr/bin/env python3\n'+shebang+f.read())
else:
if shebang != '#!/usr/bin/env python3':
with open(os.path.join(root, name), 'w') as e:
e.write('#!/usr/bin/env python3\n'+f.read())
os.chmod(os.path.join(root, name), 493)
It's working, but it will raise that error. 它正在工作,但是会引发该错误。 I don't know where is wrong. 我不知道哪里错了。
Okay, now I understand what's wrong. 好吧,现在我明白了怎么了。 Because if root[:3] == './.'
因为if root[:3] == './.'
only works when the sys.argv[1]
is .
仅在sys.argv[1]
工作.
. 。
Then, like @AnandSKumar said. 然后,就像@AnandSKumar所说的。 The program got a file that is not a text file. 程序得到的文件不是文本文件。
So now I edited my code like this: 所以现在我像这样编辑代码:
if fnmatch(root, sys.argv[1]+'/.*'):
pass
And now it's working so good, thanks @AnandSKumar. 现在,它的运行非常好,谢谢@AnandSKumar。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.