[英]Finding correct path to files in subfolders with os.walk with python?
[英]What does this error mean when I use `os.walk` to get the files path on python 3?
錯誤太長,因此我沒有將其放在標題中。 這是錯誤:
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
但是我以前從未見過此錯誤。 我寫了一個程序來自動更改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)
它正在工作,但是會引發該錯誤。 我不知道哪里錯了。
好吧,現在我明白了怎么了。 因為if root[:3] == './.'
僅在sys.argv[1]
工作.
。
然后,就像@AnandSKumar所說的。 程序得到的文件不是文本文件。
所以現在我像這樣編輯代碼:
if fnmatch(root, sys.argv[1]+'/.*'):
pass
現在,它的運行非常好,謝謝@AnandSKumar。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.